Merging two json array object based on union and intersection

馋奶兔 提交于 2019-12-25 09:12:01

问题


I am trying to merge two json array with objects as element. You may refer to this plunkr file for both json. I have succesfully retrieve the expected final outcome array id, but I do not know how to form back the expected json as below. I am using underscore js for this purpose.

Note: If object exist in newJson and not in currentJson, after merge, it will be inactive state by default.

I am not sure whether I am using the correct approach. This is what I have try:

var newJsonID = _.pluck(newJson, 'id');
var currentJsonID =  _.pluck(currentJson, 'id');
var union = _.union(newJsonID, currentJsonID);
var intersection = _.intersection(currentJsonID, newJsonID);
var final = _.difference(union, _.difference( currentJsonID, intersection);

Expected Final Outcome:

   [
    {
        "id": "12",
        "property1Name": "1"
        "status": "inactive"
    },
    {
        "id": "11",
        "property1Name": "1"
        "status": "inactive"
    },
    {
        "id": "10",
        "property1Name": "1"
        "status": "inactive"
    },
    {
        "id": "9",
        "property1Name": "1"
        "status": "active"
    }
]

回答1:


A solution in plain Javascript with two loops and a hash table for lookup.

function update(newArray, currentArray) {
    var hash = Object.create(null);
    currentArray.forEach(function (a) {
        hash[a.id] = a.status;
    });
    newArray.forEach(function (a) {
        a.status = hash[a.id] || 'inactive';
    });
}

var newJson = [{ "id": "12", "property1Name": "1" }, { "id": "11", "property1Name": "1" }, { "id": "10", "property1Name": "1" }, { "id": "9", "property1Name": "1" }],
    currentJson = [{ "id": "10", "property1Name": "1", "status": "inactive" }, { "id": "9", "property1Name": "1", "status": "active" }, { "id": "8", "property1Name": "1", "status": "active" }, { "id": "7", "property1Name": "1", "status": "inactive" }];
   
update(newJson, currentJson);
document.write('<pre>' + JSON.stringify(newJson, 0, 4) + '</pre>');


来源:https://stackoverflow.com/questions/37304104/merging-two-json-array-object-based-on-union-and-intersection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!