0

I want to merge 2 objects with nested arrays (or subarrays) by taking id property as key which is present in all the arrays. I tried using _.merge() and _.mergeWith() but both of them are either replacing the older object, or extending rather than merging the arrays or they just work on superficial level and doesn't merge deeply nested arrays. Also, merging doesn't mean I want to merge multiple subarrays into single array, but it means merging 2 objects with their respective nested arrays.

Example:

var obj1 = {arr1: [subarr1: [subarr2:[a, b]...]...]...}
var obj2 = {arr1: [subarr1: [subarr2:[a, c]...]...]...}
var obj3 = merge(obj1, obj2)
// obj3 should be {arr1: [subarr1: [subarr2:[a, b, c]...]...]...}

Mayank Kataria
  • 870
  • 2
  • 12
  • 22

1 Answers1

1

I suggest you to use deepmerge (npm install deepmerge) or deepmerge-ts (npm install deepmerge-ts).

deepmerge also comes with typings for TypeScript and is more stable (since it's older), but deepmerge-ts is also available for Deno and is faster by design, although written in TypeScript as the name implies.

Once imported you can do

deepmerge({ a: 1, b: 2, c: 3 }, { a: 2, d: 3 });

to get

{ a: 2, b: 2, c: 3, d: 3 }

This works nicely with complex objects and arrays. A real all-rounder solution this is.

Refrence

Milad Elyasi
  • 789
  • 4
  • 12
  • Hey I gave it a try and it's a nice library. But one problem is that it's creating duplicates of items rather than merging them. I want to merge them by keeping ```id``` property as key. Do you know how to achieve that? Thanks – Mayank Kataria Mar 18 '22 at 18:45
  • use reduce to collect the duplicates and save them in a temporary object with values of origin as its keys. Then iterate the keys and reconstruct the the object. – Milad Elyasi Mar 21 '22 at 20:54