您好我想转换来自 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
在您的数组和内部使用 map ,您可以匹配您选择的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 转换为字符串/数字。
关于javascript - 如何根据其他数组更改原始数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59733044/