Reputation: 11
Here is my array of object:
let a = [
{"team_id": 14, "name": "Aus"},
{"team_id":39,"name": "New"},
{"team_id": 44, "name": "Ind",}
]
let b = [{"team_id":39,"name": "New"}]
I want to find array of object b
value and add new key value to that object "selected":true
I want output like this:
let c = [
{"team_id": 14, "name": "Aus"},
{"team_id":39,"name": "New","selected":true},
{"team_id": 44, "name": "Ind",}
]
Upvotes: 1
Views: 63
Reputation: 6736
let a = [{
"team_id": 14, "name": "Aus"
}, {
"team_id": 39, "name": "New"
}, {
"team_id": 44, "name": "Ind",
}];
let b = [{
"team_id": 39, "name": "New"
}];
const result = a.map(rec => {
const isPresent = b.find(val => val.team_id === rec.team_id);
if (isPresent) {
rec.selected = true;
}
return rec;
});
console.log(result)
Upvotes: 1
Reputation: 5603
Here is the code which loop through the first array and find if the current item as a matcher in the second array if so It will return another object to which the selected
key will be added.
let a = [
{"team_id": 14, "name": "Aus"},
{"team_id":39,"name": "New"},
{"team_id": 44, "name": "Ind",}
]
let b = [{"team_id":39,"name": "New"}]
const results = a.reduce((acc, current) => {
let exists = b.find(item => item.team_id === current.team_id);
return exists? acc.concat({...current, selected: true}): acc.concat(current);
}, []);
console.log(results);
Upvotes: 0