javascript - 如何根据其他数组更改原始数组
问题描述
您好我想转换来自 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]
解决方案
您可以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 转换为字符串/数字。
推荐阅读
- google-data-studio - 限制在谷歌数据工作室中计算的行数
- javascript - 增加拼接指数的功能?
- javascript - 如何使用 java 脚本删除 django 动态表单集 - 索引问题?
- angular - 自定义指令更改输入中的数字格式并在 Angular 8 中使用计算中的数字
- flutter - 颤振从json中获取数据“字符串不是Iterable的子类型
" - mysql - SQL 根据第一个值两次从同一个表中获取不同的值
- javascript - 如何在 JavaScript 中对对象的所有值求平方?
- windows - Windows - 使用 CreateProcessWithTokenW 在会话 0 中创建一个进程
- javascript - 如何解决 Edge 和 Chrome 上的这些 html2canvas 滚动错误?
- algorithm - 在几个玩家之间获得所有可能的卡片排列