typescript - 类型“字符串 []”上不存在属性“替换”
问题描述
我正在尝试用字符串上的下划线替换空格,因为我从 API 获得的数据与我正在比较的数据存在一些差异。
我在映射数组时添加了一个属性,并且我正在使用replace
它来转换data
数组和roleIndex
数组上的角色字符串
const sortedArray = data
.map(employee => ({
...employee,
rank: roleIndex.findIndex(role => role.replace(/\s+/g, '_').includes(employee.role.replace(/\s+/g, '_'))) +1 || 100
}))
但是 TypeScript 抱怨:
`Property 'replace' does not exist on type 'string[]'.(2339)`
这是复制问题的完整代码: https ://tsplay.dev/zwODlN
- - 更新
感谢@Viet 和@Andreas 指出它们roleIndex
是数组而不是字符串,所以我添加了另一种map
方法
const sortedArray = data
.map(employee => ({
...employee,
rank: roleIndex.findIndex(role => role
.map((v) => v.replace(/\s+/g, '_'))
.includes(employee.role.replace(/\s+/g, '_'))) +1 || 100
}))
解决方案
好吧,因为 roleIndex 中的每个项目都是一个数组,而不是一个字符串:
const roleIndex = [
['Managing Director'],
['Operations Director', 'Head of Client Services'],
['Head of Sales and Marketing', 'Director of Performance and Innovation'],
['Head of Digital', 'PR and Promotion']
]
所以你必须像这样访问第一个元素:
rank: roleIndex.findIndex(role => role[0].replace(/\s+/g, '_').includes(employee.role.replace(/\s+/g, '_'))) +1 || 100
推荐阅读
- hashicorp-vault - 保险柜包装令牌 - 使用次数
- statistics - 有没有办法将 Stata 中的数据从单个观察(例如经历事件的患者数量)转换为多个观察?
- javascript - 使用 JavaScript 中的自定义键将数组转换为对象
- javascript - Javascript Self-Defending是如何工作的,它是如何在美化时进入无限循环的?
- json - 将 Json 响应中的对象列表映射到颤动中的列表
- electron - 为什么 nyc 只从我的 Electron 进程的主进程中捕获文件?
- python - 将两个连续的词视为词频中的一个
- sql - Postgresql“+”符号用于回车/zsh脚本的新行
- javascript - 为什么我不能在 jasmine 的 expectAsync 中使用匿名函数?
- mips - 我如何将 1 添加到内存中的第一个值并将该值存储在相邻的单词中,并将该值的副本放入寄存器 $v0