[英]Merging two nested objects and concatenate arrays in side
Is there a build in method that merge two nested objects I make across Object.assign()
. 有没有内置方法来合并我在
Object.assign()
创建的两个嵌套对象。
It is not working in my case because my nested object is array
. 在我的情况下,它不起作用,因为我的嵌套对象是
array
。
var obj1 = {
"name": "Services",
"category": "Services",
"subCategory": [{
"name": "Negative",
"category": "Negative",
"subCategory": [{ // only this part differ
"name": "Expensive",
"val": 109,
"subCategory": null
}]
}]
};
var obj2 = {
"name": "Services",
"category": "Services",
"subCategory": [{
"name": "Negative",
"category": "Negative",
"subCategory": [{ // only this part differ
"name": "Disorganized",
"val": 25,
"subCategory": null
}]
}]
};
It should merge like this 它应该像这样合并
var result = {
"name": "Services",
"category": "Services",
"subCategory": [{
"name": "Negative",
"category": "Negative",
"subCategory": [{ // array concatenation
"name": "Disorganized",
"val": 25,
"subCategory": null
}, {
"name": "Expensive",
"val": 109,
"subCategory": null
}]
}]
};
Its just a proposal how to deal with same properties and same values and this special data structure, 'name'
and 'subCategory'
. 这只是一个建议,即如何处理相同的属性和相同的值以及这种特殊的数据结构
'name'
和'subCategory'
。
{
"name": "Services",
"subCategory": [
{
"name": "Negative", ...
"subCategory": [
{
"name": "Expensive", ...
},
{
"name": "Disorganized", ...
}
]
}
]
}
This solution works with a recursion and adds the elements of 'subCategory'
if the name does not match. 此解决方案与递归一起使用,并在名称不匹配时添加
'subCategory'
的元素。
function fuse(target, source) { if (target.name === source.name) { source.subCategory.forEach(function (a) { target.subCategory.some(function (b) { return fuse(b, a); }) || (target.subCategory = target.subCategory.concat(source.subCategory)); }); return true; } } var obj1 = { "name": "Services", "category": "Services", "subCategory": [{ "name": "Negative", "category": "Negative", "subCategory": [{ "name": "Expensive", "val": 109, "subCategory": null }] }] }, obj2 = { "name": "Services", "category": "Services", "subCategory": [{ "name": "Negative", "category": "Negative", "subCategory": [{ "name": "Disorganized", "val": 25, "subCategory": null }] }] }; fuse(obj1, obj2); document.write('<pre>' + JSON.stringify(obj1, 0, 4) + '</pre>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.