Derik
Derik

Reputation: 11

How to add object value dynamically in array of objects

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

Answers (2)

Sarun UK
Sarun UK

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

Yves Kipondo
Yves Kipondo

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

Related Questions