2016-05-18 122 views
0

我想将两个json数组与对象合并为元素。您可以参考这两个json的plunkr file。我已成功检索预期的最终结果数组ID,但我不知道如何形成预期的JSON,如下所示。我正在为此使用下划线js。基于并集和交集合并两个json数组对象

注意:如果对象存在于newJson中而不存在于currentJson中,则合并后默认为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" 
    } 
] 
+0

你从哪里得到的状态?我的意思是用同样的'id'? –

+0

@NinaScholz你的意思是我从哪里获得预期最终结果的状态?如果newJson中的id确实存在于currentJson中,则使用相同id的currentJson状态,否则默认为inactive。 – vincentsty

+0

你只对下划线解决方案感兴趣吗? –

回答

1

纯JavaScript中的解决方案有两个回路和查找哈希表。

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

+0

糟糕。我错过了最终预期解决方案中的property1Name。基本上,新的Json可以有很多属性名称,例如:property1Name,property2Name等,而currentJson将有额外的1个属性,这是状态。根据你给出的这个解决方案,我必须硬编码'return {id:a.id,property1Name:a.property1Name,status:hash [a.id]}',这对我来说似乎并不是最优的,因为当额外的属性被添加到JSON中(从数据库retreive),我不得不改变JavaScript中的代码,否则将不会被反映。有没有可能的解决方案来避免这种情况? – vincentsty

+0

你想只添加状态属性到'newJson'吗? –

+0

基本上,最终结果应该具有newJson plus状态中可用的所有现有属性。 – vincentsty