對於什麼它的價值,沒有圖書館,只是香草JS
函數,它的工作:
function mergeObjArrays(list1, list2) {
var mergedList = [],
i = 0,
j = 0,
k = 0,
l1 = list1.length,
l2 = list2.length,
listMatchFound = false,
mergedObj,
mergeMatchFound = false;
for (i = 0; i < l1; i++) {
for (j = 0; j < l2; j++) {
if (list1[i].id === list2[j].id) {
listMatchFound = true;
mergedObj = mergeObj(list1[i], list2[j]);
for (k = 0; k < mergedList.length; k++) {
if (mergedList[k].id === mergedObj.id) {
mergedObj = mergeObj(mergedList[k], mergedObj);
mergedList[k] = mergedObj;
mergeMatchFound = true;
break;
}
}
if (!mergeMatchFound) {
mergedList.push(mergedObj);
} else {
mergeMatchFound = false; //reset ready for another iteration
}
}
}
if (!listMatchFound) {
mergedList.push(list1[i]);
} else {
listMatchFound = false; //reset ready for another iteration
}
}
return mergedList;
function mergeObj(obj1, obj2) {
for (var o in obj1) {
obj2[o] = obj1[o];
}
return obj2;
}
}
用法示例
var a = [
{"id": 1, "name": "yadda", "description": "yadda yadda"},
{"id": 2, "name": "yadda1", "description": "yadda yadda1"},
{"id": 7, "name": "yadda2", "description": "yadda yadda2"},
{"id": 10, "name": "yadda3", "description": "yadda yadda3"}
];
var b = [
{"id": 7, "icon": "icon3.gif"},
{"id": 10, "icon": "icon4.gif"},
{"id": 2, "icon": "icon2.gif"},
{"id": 2, "title": "Number 2 title"},
{"id": 1, "icon": "icon1.gif"}
];
//used like
var result = mergeObjArrays(a,b);
console.log(result)
//outputs (although not necessarily in order)
[
{"id": 1, "name": "yadda", "description": "yadda yadda","icon": "icon1.gif"},
{"id": 2, "name": "yadda1", "description": "yadda yadda1","icon": "icon2.gif","title": "Number 2 title"},
{"id": 7, "name": "yadda2", "description": "yadda yadda2","icon": "icon3.gif"},
{"id": 10, "name": "yadda3", "description": "yadda yadda3","icon": "icon4.gif"}
]
這將ineffect做基於對象合併在set1中(在這個例子中是a)(即,如果在set1中包含對象,或者如果在set1和set2中都包含合併對象,而不是如果它僅在set2中出現),並且處理1對多關係作爲好(即set2中的一個對象的多個實例將被合併到一個具有set1的obj的對象中),並且對象的順序無關緊要。你甚至可以更進一步,傳入兩個對象中的關鍵字(通用元素),在本例中,「id」被硬連線到mergeObjArrays函數。
http://docs.angularjs.org/api/ng/function/angular.extend – Whisher
http://underscorejs.org/#extend – blakev
是兩個列表總是以相同的順序排列(並且包含相同的ID),還是需要首先[查找](http://underscorejs.org/#find)? – Bergi