javascript - 使用 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 }],
},
],
},
};
我错过了什么吗?
解决方案
在文档的这一部分中,它提到
默认情况下,数组是通过连接它们来合并的。
所以你必须提供另一个选项来覆盖这个默认行为,这在下面提到,通过使用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>
推荐阅读
- excel - 根据某个单元格中的文本值清除某些列中的某些单元格的代码
- python - 如何修复 AttributeError:“StringVar”对象没有属性“_name”
- c++ - 在 C++ 中读取二进制文件会返回意外值
- python - 习惯函数 Python 3.7
- javascript - 您如何将光标聚焦在位于 Bootstrap 模式中的 Quill 编辑器中?
- sql - 透视 SQL Server 表
- javascript - 如何使用 If () javascript 检查类是否被点击
- java - Android Studio com.google.wireless.android.sdk.stats.IntellijIndexingStats
- azure - Azure devops 构建推送映像到 aks
- wordpress - 如何检查文件是否真的存在于 WordPress 中?