首页 > 解决方案 > 使用 deepmerge 将嵌套对象与对象数组合并

问题描述

我正在使用库https://www.npmjs.com/package/deepmerge将两个嵌套对象与对象数组深度合并,但我没有得到预期的结果。

       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));给我这个结果:

        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 }],
                    },
                  ],
                },
              };

但我希望这样:

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

我错过了什么吗?

标签: javascriptarraysobjectmergearray-merge

解决方案


文档的这一部分中,它提到

默认情况下,数组是通过连接它们来合并的。

所以你必须提供另一个选项来覆盖这个默认行为,这在下面提到,通过使用arrayMerge选项

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/deepmerge@4.2.2/dist/umd.js"></script>


推荐阅读