Home > database >  Merge nested object with array of objects with deepmerge
Merge nested object with array of objects with deepmerge

Time:09-25

I am using library https://www.npmjs.com/package/deepmerge to deep merge two nested objects with array of objects but I am not getting expected result.

       const x = {
                foo: { bar: 1 },
                loo: {
                  array: [
                    {
                      too: [{ bar: 1 }, { bar: 2 }, { bar: 3 }, { bar: 4 }, { bar: 5 }],
                    },
                  ],
                },
              };

              const y = {
                foo: { bar: 4 },
                loo: {
                  array: [
                    {
                      too: [{ bar: 1 }, { bar: 2 }, { bar: 3 }, { bar: 4 }, { bar: 5 }],
                    },
                  ],
                },
              };

and console.log(deepmerge(x, y)); gives me this result:

        const result = {
                foo: { bar: 4 },
                loo: {
                  array: [
                    {
                      too: [{ bar: 1 }, { bar: 2 }, { bar: 3 }, { bar: 4 }, { bar: 5 }],
                    },
                    {
                      too: [{ bar: 1 }, { bar: 2 }, { bar: 3 }, { bar: 4 }, { bar: 5 }],
                    },
                  ],
                },
              };

but I would expect this:

              const expectedResult = {
                foo: { bar: 4 },
                loo: {
                  array: [
                    {
                      too: [{ bar: 1 }, { bar: 2 }, { bar: 3 }, { bar: 4 }, { bar: 5 }],
                    },
                  ],
                },
              };

Am I missing something?

CodePudding user response:

In this section of the doc, it mentions that

By default, arrays are merged by concatenating them.

So you have to provide another option to override this default behavior, this is mentioned below, by using arrayMerge option

const x = { foo: { bar: 1 }, loo: { array: [{ too: [{ bar: 1 }, { bar: 2 }, { bar: 3 }, { bar: 4 }, { bar: 5 }], }, ], }, };
const y = { foo: { bar: 4 }, loo: { array: [{ too: [{ bar: 1 }, { bar: 2 }, { bar: 3 }, { bar: 4 }, { bar: 5 }], }, ], }, };

console.log(
  deepmerge(
    x,
    y,
    { arrayMerge: (destinationArray, sourceArray, options) => sourceArray }
  )
);
<script src="https://unpkg.com/[email protected]/dist/umd.js"></script>

  • Related