2016-05-18 124 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