-1

I'm working on a nodejs app and need to join two document arrays together. i have an id field that can be use for joining but am unsure of how to achieve the desired output elegantly. See example arrays below.

array 1
[{"id": 1,
  "name": "paul"
 },
{"id": 2,
  "name": "sarah"
 }
]

array 2
[{"id": 1,
  "email": "p@test.co.uk"
 },
{"id": 2,
  "email": "s@test.co.uk"
 }
]

output
[{"id": 1,
  "name": "paul",
  "email": "p@test.co.uk"
 },
{"id": 2,
  "name": "sarah",
  "email": "s@test.co.uk"
 }
]
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Mish
  • 103
  • 5
  • Hi! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Nov 16 '18 at 10:31
  • 1
    Possible duplicate of [JavaScript merging objects by id](https://stackoverflow.com/questions/19480008/javascript-merging-objects-by-id) – Hassan Imam Nov 16 '18 at 10:32

2 Answers2

0

You can use Object.assign method in combination with map function in order to achieve your desired output.

For map method you have to pass a callback provided function as argument which is applied for every item from your given array.

arr1 = [{"id": 1, "name": "paul" }, {"id": 2, "name": "sarah" } ], arr2 = [{"id": 1, "email": "p@test.co.uk" }, {"id": 2, "email": "s@test.co.uk" } ]

let final = arr1.map(function(item){
  return Object.assign(item, arr2.find(({id}) => id == item.id));
});

console.log(final);

Or simply use an arrow function.

arr1 = [{"id": 1, "name": "paul" }, {"id": 2, "name": "sarah" } ], arr2 = [{"id": 1, "email": "p@test.co.uk" }, {"id": 2, "email": "s@test.co.uk" } ]

let final = arr1.map((item) => Object.assign(item, arr2.find(({id}) => id == item.id)));
console.log(final);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

You can simply achieve that using a combination of ES6 map, find and Object.assign:

let output = array1.map((item1) => 
    Object.assign({}, item1, array2.find((item2) => 
        item1.id == item2.id
    ))
);

Source: Array.prototype.map, Array.prototype.find, Object.assign

Szab
  • 1,263
  • 8
  • 18