我有以下两个数组,我想得到第二个数组,但是匹配的对象应该包含一个额外的键 "select": true, 不匹配的对象应该包含 "select": 假。
var firstArray = [{id: -1, type: "group"},
{id: -2, type: "group"}];
var secondArray = [{id: -3, type: "group"},
{id: -2, type: "group"},
{id: -1, type: "group"}];
预期结果:
var expectedArray = [{id: -1, type: "group", select: true},
{id: -2, type: "group", select: true},
{id: -3, type: "group", select: false}];
我试过下面的代码:
for(var i=0;i<firstArray.length;i++){
for(var j=0;j<secondArray.length;j++){
console.log(firstArray[i].id,secondArray[j].id)
if(firstArray[i].id===secondArray[j].id){
if(secondArray[j].hasOwnProperty('select')){
secondArray[j].select=true;
// console.log('true select property',secondArray[j].select)
}
else{
secondArray[j].select=true;
// console.log('true adding new',secondArray[j].select)
}
}else{
secondArray[j]['select']=false;
// console.log('false not match',secondArray[j].select)
}
}
}
最佳答案
您可以创建一个 Set
firstArray
中存在的所有 id。然后使用 forEach
遍历 secondArray
并根据集合 has
是否添加 select
值。身份证
let firstArray=[{id:-1,type:"group"},{id:-2,type:"group"}],
secondArray=[{id:-3,type:"group"},{id:-2,type:"group"},{id:-1,type:"group"}];
const ids = new Set(firstArray.map(a => a.id));
secondArray.forEach(a => a.select = ids.has(a.id))
console.log(secondArray)
关于javascript - 用另一个对象数组过滤对象数组,并为匹配的对象添加额外的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55866218/