3 回答

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以使用.map迭代arr1并.includes檢查該項(xiàng)目是否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貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
您還可以使用 some
如下方法:
const newArr = arr1.map(item => { return { ...item, favorite: arr2.some(elem => elem === item.id) } })

TA貢獻(xiàn)1833條經(jīng)驗(yàn) 獲得超4個(gè)贊
您還可以使用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);
添加回答
舉報(bào)