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]...]...]...}

1 Answer 1

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

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

2 Comments

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
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.

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.