我有两个数组。let arr1 = [{id: 1, favorite: false}, {id: 2, favorite: false}, {id: 3, favorite: false}];
let arr2 = [1, 3];如果 id 存在于 中arr2,我想将(该特定对象的)更改favorite为true例如。在上面的例子中,最终的结果arr1会是这样的[{id: 1, favorite: true}, {id: 2, favorite: false}, {id: 3, favorite: true}];
3 回答
郎朗坤
TA贡献1921条经验 获得超9个赞
您可以使用.map迭代arr1并.includes检查该项目是否id位于arr2:
const arr1 = [
{id: 1, favorite: false},
{id: 2, favorite: false},
{id: 3, favorite: false}
];
const arr2 = [1, 3];
const res = arr1.map(e =>
({...e, favorite: arr2.includes(e.id)})
);
console.log(res);
绝地无双
TA贡献1946条经验 获得超4个赞
您还可以使用 some
如下方法:
const newArr = arr1.map(item => { return { ...item, favorite: arr2.some(elem => elem === item.id) } })
潇潇雨雨
TA贡献1833条经验 获得超4个赞
您还可以使用forEach和includes。
let arr1 = [{id: 1, favorite: false}, {id: 2, favorite: false}, {id: 3, favorite: false}];
let arr2 = [1, 3];
arr1.forEach(x => x.favorite = arr2.includes(x.id))
console.log(arr1);
添加回答
举报
0/150
提交
取消