今天我们分享的是,如何使用javascript来将两个含有相同键值的json合并为一个数组。
已知arr1的长度和arr2相等,arr1和arr2含有相同的键值id,使用js如何得到merge。
如下数据:
var merge= [{id: 12,name: 20,title: 500}, {id: 13,name: 30,title: 666}];
下面是实现过程。
<script> var arr1 = [{ id: 12, name: 20 }, { id: 13, name: 30 }]; var arr2 = [{ id: 12, title: 500 }, { id: 13, title: 666 }]; var merge = [], kvIndex = {}; for (var i = 0; i < arr1.length; i++) { for (var j = 0; j < arr2.length; j++) { if (arr1[i].id == arr2[j].id) { var item if (kvIndex[arr1[i].id] == undefined) { kvIndex[arr1[i].id] = merge.length; item = {}; for (var attr in arr1[i]) item[attr] = arr1[i][attr]; merge[kvIndex[arr1[i].id]] = item; } else item = merge[kvIndex[arr1[i].id]]; for (var attr in arr2[j]) item[attr] = arr2[j][attr]; } } } console.log(merge) </script>
文摘原创自http://www.santii.com/article/148.html