首页 > 解决方案 > 类型“字符串 []”上不存在属性“替换”

问题描述

我正在尝试用字符串上的下划线替换空格,因为我从 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
  }))

标签: typescript

解决方案


好吧,因为 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

推荐阅读