我正在尝试将两个对象与包含对象合并..其中包含对象数组..你明白了。但是,我的代码没有产生期望的结果,我不明白为什么......可能是因为我刚刚开始使用 lodash 并且我错过了一些明显的东西
这是我要合并的两个对象
var original = {
a: "bbbb",
Id: 1,
b: {
a: "bbb",
Id: 2
},
c: "aaa",
d: [
{
a: "bbbb",
Id: 1,
b: {
a: "bbb",
Id: 2
},
c: "aaa"
},
{
a: "bbbb",
Id: 2,
b: {
a: "bbb",
Id: 3
},
c: "aaa"
}
]
};
var source = {
a: "aaa",
Id: 1,
b: {
a: "aaa",
Id: 2
},
c: null,
d: [
{
a: "aaa",
Id: 1,
b: {
a: "aaa",
Id: 2
},
c: null
},
{
a: "aaa",
Id: 2,
b: {
a: "aaa",
Id: 3
},
c: null
}
]
};
结果对象应该只包含“aaa”作为值,并且没有空值。(从“源”获取值,除非它为空并且不复制只是复制数组,而是合并其中的对象..)我的代码合并对象很好......但是,当它到达对象数组时,它无法产生正确的结果
结果应该是:
{"a":"aaa",
"Id":1,
"b":
{
"a":"aaa",
"Id":2
},
"c":"aaa",
"d":
[
{
"a":"aaa",
"Id":1,
"b":
{
"a":"aaa",
"Id":2
},
"c":"aaa"
},
{ “a”:“aaa”, “身份证”:2, “b”: { “a”:“aaa”, “身份证”:3 }, “c”:“aaa” } ]}
这是我的代码:https://jsfiddle.net/yodfcn6e/
谢谢!
最佳答案
您可以迭代对象的键,并且仅当目标具有 null
值时才进行更新。
function update(source, target) {
Object.keys(source).forEach(function (k) {
if (target[k] === null) {
target[k] = source[k];
return;
}
if (source[k] && typeof source[k] === 'object') {
update(source[k], target[k]);
}
});
}
var source = { a: "bbbb", Id: 1, b: { a: "bbb", Id: 2 }, c: "aaa", d: [{ a: "bbbb", Id: 1, b: { a: "bbb", Id: 2 }, c: "aaa" }, { a: "bbbb", Id: 2, b: { a: "bbb", Id: 3 }, c: "aaa" }] },
target = { a: "aaa", Id: 1, b: { a: "aaa", Id: 2 }, c: null, d: [{ a: "aaa", Id: 1, b: { a: "aaa", Id: 2 }, c: null }, { a: "aaa", Id: 2, b: { a: "aaa", Id: 3 }, c: null }] };
update(source, target);
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 深度合并两个 javascript 对象 lodash/vanilla,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46202433/