-2

Input arrays

arr1=[{"CATALOG":"book1","ID":"1"},{"CATALOG":"book2","ID":"2"},{"CATALOG":"book3","ID":"3"},{"CATALOG":"book4","ID":"12"}]
arr2=[{"NAME":"TOM","ID":"1"},{"NAME":"STEVE","ID":"22"},{"NAME":"HARRY","ID":"2"},{"NAME":"TIM","ID":"3"},{"NAME":"DAVE","ID":"12"},{"NAME":"WIL","ID":"12"},{"NAME":"PETER","ID":"94"},{"NAME":"SAVANNAH","ID":"77"}]
Expected Output
[{"CATALOG":"book1","ID":"1","NAME":"TOM"},
{"CATALOG":"book2","ID":"2","NAME":"HARRY"},
{"CATALOG":"book3","ID":"3","NAME":"TIM"},
{"CATALOG":"book4","ID":"12","NAME":"WIL"}

expected output is that 2 arrays have to be combined based on id. If ID doesn't exist then that particular object is skipped

I tried using

[arr1,arr2].reduce((a, b) => a.map((c, i) => Object.assign({}, c, b[i])));

But not getting the desired output

0

2 Answers 2

1

You can use map and find

const arr1 = [
  { CATALOG: "book1", ID: "1" },
  { CATALOG: "book2", ID: "2" },
  { CATALOG: "book3", ID: "3" },
  { CATALOG: "book4", ID: "12" },
];

const arr2 = [
  { NAME: "TOM", ID: "1" },
  { NAME: "STEVE", ID: "22" },
  { NAME: "HARRY", ID: "2" },
  { NAME: "TIM", ID: "3" },
  { NAME: "DAVE", ID: "12" },
  { NAME: "WIL", ID: "12" },
  { NAME: "PETER", ID: "94" },
  { NAME: "SAVANNAH", ID: "77" },
];



const output = arr1.map(a => ({
  ...a,
  NAME: arr2.find(x => x.ID === a.ID).NAME,
}));

console.log(output);

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

Comments

0

There may be cleverer solutions, but assuming arr2 always contains the corresponding ID, I'd do it simply with :

const arr1=[{"CATALOG":"book1","ID":"1"},{"CATALOG":"book2","ID":"2"},{"CATALOG":"book3","ID":"3"},{"CATALOG":"book4","ID":"12"}];
const arr2=[{"NAME":"TOM","ID":"1"},{"NAME":"STEVE","ID":"22"},{"NAME":"HARRY","ID":"2"},{"NAME":"TIM","ID":"3"},{"NAME":"DAVE","ID":"12"},{"NAME":"WIL","ID":"12"},{"NAME":"PETER","ID":"94"},{"NAME":"SAVANNAH","ID":"77"}];

const output = arr1.map(obj1 => {
  const obj2 = arr2.find(o2 => o2.ID === obj1.ID);
  return Object.assign(obj1, obj2)
});

console.log(output)

Or as a one-liner :

const output = arr1.map(obj1 => Object.assign(obj1, arr2.find(o2 => o2.ID === obj1.ID)))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.