Reputation: 69
const arr1 = [{id:1, checked:false},{id:2, checked:false},{id:3, checked:false}]
const arr2 = [{id:1},{id:3}]
i have 2 arrays like above. i want to result should be
arr1 = [{id:1, checked:true},{id:2, checked:false},{id:3, checked:true}]
i tried with array filter, but it gives joined array
companyArr.forEach(citem => {
mapItem.forEach(mitem => {
companyArr.push({
Id: citem.Id,
CompanyName: citem.CompanyName,
isChecked: (mitem.company_id === citem.Id)
})
})
})
Upvotes: 1
Views: 57
Reputation: 50759
You could make a Set which keeps all your ids from each object in arr2
, and then use .map()
on arr1
to check the checked
values based on whether the set has the current objects id:
const arr1 = [{id:1, checked:false},{id:2, checked:false},{id:3, checked:false}]
const arr2 = [{id:1},{id:3}];
const lut = new Set(arr2.map(({id}) => id));
const res = arr1.map(o => ({...o, checked: lut.has(o.id)}))
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore */
Note: I've created a set here for efficient lookup, however, you could use .some()
on arr2 if you wish in the .map()
as well, but this would have performance drawbacks for large data sets:
const arr1 = [{id:1, checked:false},{id:2, checked:false},{id:3, checked:false}]
const arr2 = [{id:1},{id:3}];
const res = arr1.map(o => ({...o, checked: arr2.some(({id}) => id === o.id)}));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore */
Upvotes: 2
Reputation: 10662
You can use map
and find
for that.
const arr1 = [{ id: 1, checked: false }, { id: 2, checked: false }, { id: 3, checked: false }]
, arr2 = [{ id: 1 }, { id: 3 }]
, result = arr1.map(el => ({ ...el, checked: !!arr2.find(({ id }) => id === el.id) }));
console.log(result);
Upvotes: 1
Reputation: 22500
you could use Array#map
for recreate the array .And Array#findIndex
for find the first array value exist on 2nd array .And use Spread operator for easy to split the object
const arr1 = [{id:1, checked:false},{id:2, checked:false},{id:3, checked:false}]
const arr2 = [{id:1},{id:3}]
let res = arr1.map(a=> ({...a,checked: arr2.findIndex(({id}) => id == a.id) > -1}));
console.log(res)
Upvotes: 1