0

What's the best way to merge 2 disparate data sets in javascript? For example,

const parentRecords = [{
   id: 1,
   mycol1: 'parent name',
}]

const childRecords = [{
   childid: 2,
   parentId: 1,
   mycol2: 'child name',
}]

const mergedRecords = [...parentRecords, ...childRecords]

This code returns an array where each of the records above exist as separate rows. I need the result to look like this:

[{
   id: 1,
   mycol1: 'parent name',
   childid: 2,
   parentId: 1,
   mycol2: 'child name',
}]
iron.man.rball
  • 109
  • 1
  • 5

1 Answers1

1

You didn't specify on which criteria items should be merged. In my answer I'm assuming it's based on the parent id and the children parentId:

const parentRecords = [{
   id: 1,
   mycol1: 'parent name',
}];

const childRecords = [{
   childid: 2,
   parentId: 1,
   mycol2: 'child name',
}];

const result = parentRecords.map((x) =>
  Object.assign(
    x,
    childRecords.find((y) => y.parentId === x.id)
  )
);

console.log(result);
Guerric P
  • 30,447
  • 6
  • 48
  • 86