下面是我的兩個數組。我想比較它們,結果數組應包含更新的值.Id的常見.. 數組跨越n層,即,沒有固定的水平..比較兩個數組,並通過保留現有對象使用javascript來更新新值使用javascript
第一陣列即,更新用前陣..
var parentArray1=[
{
"id": 1,
"name": "test",
"context": [
{
"id": 1.1,
"name": "test 1.1"
}
]
},
{
"id": 2,
"name": "test"
},
{
"id": 3,
"name": "test",
"context": [
{
"id": 3.1,
"name": "test 3.1"
}
]
},
{
"id": 4,
"name": "test"
}
]
,我執行被
1.Adding一個新的操作Item 2.Upda婷現有項目
由於這兩個操作所改變的值,我會在不同的陣列會越來越.. 即的結果,
var changedArray=
[
{
"id": 1,
"name": "test1",
"context": [
{
"id": 1.1,
"name": "Changed test 1.1"
}
]
},
{
"id": 5,
"name": "test5"
}
]
現在我已經寫了通過循環的通用功能parentArray1並使用所述唯一propertiesI需要或者在changedArray在任何級別
所得陣列應增加一個新項目時,如果該項目是有或更新現有的項目..
[
{
"id": 1,
"name": "test",
"context": [
{
"id": 1.1,
"name": "Changed test 1.1"
}
]
},
{
"id": 2,
"name": "test"
},
{
"id": 3,
"name": "test",
"context": [
{
"id": 3.1,
"name": "test 3.1"
}
]
},
{
"id": 4,
"name": "test"
},
{
"id": 5,
"name": "test5"
}
]
通用功能:
compareArray(parentArray1, changedArray, ["id"]);
function compareArray(array1, array2, propertyArray) {
var newItem = new Array();
array2.map(function(a1Item) {
array1.map(function(a2Item) {
/If array loop again/
if (a2Item.constructor === Array) {
compareArray(a2Item, a1Item)
} else {
/loop the property name to validate/
propertyArray.map(function(property) {
if (a2Item[property]) {
if (a2Item[property] === a1Item[property]) {
a2Item = a1Item
} else {
var isAvailable = _.find(newItem, function(item) {
return item[property] === a1Item[property]
})
if (!isAvailable) {
newItem.push(a1Item);
}
}
}
})
}
});
});
/Insert the new item into the source array/
newItem.map(function(item) {
array1.push(item);
});
console.log("After Compare : " + array1);
}
您共享的代碼具有額外的功能,以防數組中的項目也是數組。你想保存嗎?另外,讓我們假設你有一些像'{a:{b:'value'}}'作爲array2中的項目。如果要更新原始對象中的a的值,是否要用'='更新它,這意味着您只更新對象的引用,或者是否要克隆'{b:'value' }對象,並有另一個具有相同值的實例? –
在我的情況下,數組嵌套有不同的屬性,如果值是對象,那麼我們應該克隆。數組中唯一的標識符是屬性名稱,即。,ID的 – forgottofly
我認爲你的問題太複雜了,難道你不能確定你遇到的確切問題?什麼不像你認爲的那樣工作? – froginvasion