将两个复杂对象合并在一起不起作用:Javascript [英] Clubbing both complex objects does not work: Javascript
问题描述
我有一个具有以下结构的源对象
I have an source object that has the following structure
var obj1 = {
type: "type1",
nested: {
level1: [
{ field: "field1", value: "val1"},
{ field: "field2", value: "val2"},
{
level2: [
{
field: "abc",
value: "11",
},
{
field: "abc",
value: "12",
}
]
}
]
},
in: 0,
out: 20
};
还有一个输入对象,应该基于该对象进行合并
Also there is an input object, based on which merging should happen
var obj2 = {
type: "type1",
nested: {
level1: [
{ field: "field1", value: "val1"},
{ field: "field3", value: "val5" }
]
},
in: 0,
out: 20
};
基于新对象,我需要合并,结果应该只包含唯一的对象.就我而言,该对象可以深入到2级.我唯一需要的是对嵌套"对象的操作.如果存在相同的键,则更新该值,否则只需附加它即可. obj2的嵌套"中的内容也始终位于obj1的嵌套"中.如果obj1的嵌套"中不存在obj2的嵌套",则删除该对象.沙箱中随附的测试用例文件
Based on the new object I need to merge and resultant should hold only the unique one's. In my case the object can go deep upto level 2. The only thing I need is a manipulation on "nested" object. If same keys are present then update the value, else just append it. Also content within "nested" of obj2 will always be there in obj1's "nested". If something of obj2's "nested" is not present in obj1's "nested" then delete that object. Test cases file attached inside sandbox
输出应如下所示:
result = {
type: "type1",
nested: {
level1: [
{ field: "field1", value: "val1"},
{ field: "field2", value: "val2"},
{ field: "field3", value: "val5" },
{
level2:
[
{
field: "abc",
value: "11",
},
{
field: "abc",
value: "12",
}
]
}
]
},
in: 0,
out: 20
};
我尝试过的方法:
const merged = [...new Set([...obj1.nested.level1, ...obj2.nested.level1])]
沙箱: https://codesandbox.io/s/angry-liskov-e5m1m
推荐答案
只是Google的深度合并javascript"或合并嵌套对象". 这里是我发现的一个例子:
Just google "deep merge javascript" or "merge nested objects". Here is one example of what i found:
// Merge a `source` object to a `target` recursively
const merge = (target, source) => {
// Iterate through `source` properties and if an `Object` set property to merge of `target` and `source` properties
for (const key of Object.keys(source)) {
if (source[key] instanceof Object) Object.assign(source[key], merge(target[key], source[key]))
}
// Join `target` and modified `source`
Object.assign(target || {}, source)
return target
}
console.log(merge(obj1, obj2));
这篇关于将两个复杂对象合并在一起不起作用:Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!