首页 > 解决方案 > 如何根据其他数组更改原始数组

问题描述

您好我想转换来自 API 的原始数组,并在他们的 id 匹配时将用户颜色字段更改为“主要”。我试图运行这段代码,但是它会重新运行空数组

console.log(array.filter((item, i) => {
  return item.id === selected[i]
}))
// Original array
[
  {
    "id": "183",
    "fullName": "Simon Aaman",
    "color": "secondary"
  },
  {
    "id": "77",
    "fullName": "Dennis Bergkamp",
    "color": "secondary"
  },
  {
    "id": "80",
    "fullName": "Allison Bäcker",
    "color": "secondary"
  },
]
/array of ids
const selected = [77, 80]

标签: javascript

解决方案


您可以color在数组和内部使用映射来更改您可以与您选择的 id 匹配的映射。

const arr = [
  {
    "id": "183",
    "fullName": "Simon Aaman",
    "color": "secondary"
  },
  {
    "id": "77",
    "fullName": "Dennis Bergkamp",
    "color": "secondary"
  },
  {
    "id": "80",
    "fullName": "Allison Bäcker",
    "color": "secondary"
  },
];
const selected = [77, 80];

const result = arr.map((el) => {
  if(selected.includes(Number(el.id))){
    return {
      ...el,
      color: 'primary'
    }
  }
  return el;
});

console.log(result);
此外,您的代码有问题,您正在严格检查 id,===这意味着您也在寻找类型(一个是数字,一个是字符串),您可以使用==不检查类型或只需将其中一个 id 转换为字符串/数字。


推荐阅读