簡體   English   中英

合並兩個嵌套對象並在側面連接數組

[英]Merging two nested objects and concatenate arrays in side

有沒有內置方法來合並我在Object.assign()創建的兩個嵌套對象。
在我的情況下,它不起作用,因為我的嵌套對象是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
    }]
  }]
};  

它應該像這樣合並

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

這只是一個建議,即如何處理相同的屬性和相同的值以及這種特殊的數據結構'name''subCategory'

{
    "name": "Services",
    "subCategory": [
        {
            "name": "Negative", ...
            "subCategory": [
                {
                    "name": "Expensive", ...
                },
                {
                    "name": "Disorganized", ...
                }
            ]
        }
    ]
}

此解決方案與遞歸一起使用,並在名稱不匹配時添加'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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM