有一个对象数组var objArray = [{name: orange, id: 1},{name : apple, id:2},{name: banana, id:3},{name: grapes, id:4}]和一个 id 数组var arrId = [1,4]如何过滤以从对象数组中获取匹配 id 的相应对象?预期的:var result = [{name: orange, id: 1}, {name: grapes, id:4}]试过:objArray.filter(o => o.id === arrId);
1 回答
猛跑小猪
TA贡献1858条经验 获得超8个赞
你可以检查一下Array#includes
。
var objArray = [{ name: 'orange', id: 1 }, { name: 'apple', id: 2 }, { name: 'banana', id: 3 }, { name: 'grapes', id: 4 }],
arrId = [1, 4],
result = objArray.filter(o => arrId.includes(o.id));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报
0/150
提交
取消