根据并集和交集合并两个 json 数组对象

Merging two json array object based on union and intersection

我正在尝试将两个 json 数组与对象合并为元素。 json 都可以参考这个 plunkr file。我已成功检索到预期的最终结果数组 ID,但我不知道如何返回预期的 json,如下所示。为此,我正在使用下划线 js。

注意:如果object存在newJson中,currentJson中不存在,merge后默认为inactive状态

我不确定我使用的方法是否正确。这是我尝试过的:

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);

预期最终结果:

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

一个简单的 Javascript 解决方案,带有两个循环和一个哈希 table 用于查找。

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>');