1

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",}
] 

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.