我有一个api的JSON数组,其结构如下:
newArray = [
{
"item":{"id":1, "name":"item1"},
"type": [1,2,3]
},
{
"item":{"id":2, "name":"item2"},
"type": [4,5]
},
{
"item":{"id":3, "name":"item3"},
"type": [8,9]
},
{
"item":{"id":1, "name":"item1"},
"type": [11,12]
},
{
"item":{"id":2, "name":"item3"},
"type": [31,41]
},
{
"item":{"id":3, "name":"item3"},
"type": [11,23]
}
]
我想返回一个对象中具有相同
name
和id
的对象的数组。resultArray = [
{
"item":{"id":1, "name":"item1"},
"type": [1,2,3,11,12]
},
{
"item":{"id":2, "name":"item2"},
"type": [4,5,31,41]
},
{
"item":{"id":3, "name":"item3"},
"type": [8,9,11,23]
}]
最佳答案
这是一个带有Array#forEach()
和帮助对象的单循环建议,用于引用插入的项目。
var newArray = [{ "item": { "id": 1, "name": "item1" }, "type": [1, 2, 3] }, { "item": { "id": 2, "name": "item2" }, "type": [4, 5] }, { "item": { "id": 3, "name": "item3" }, "type": [8, 9] }, { "item": { "id": 1, "name": "item1" }, "type": [11, 12] }, { "item": { "id": 2, "name": "item3" }, "type": [31, 41] }, { "item": { "id": 3, "name": "item3" }, "type": [11, 23] }],
resultArray = [];
newArray.forEach(function (a) {
if (!this[a.item.id]) {
this[a.item.id] = { item: a.item, type: [] };
resultArray.push(this[a.item.id]);
}
this[a.item.id].type = this[a.item.id].type.concat(a.type);
}, Object.create(null));
document.write('<pre>' + JSON.stringify(resultArray, 0, 4) + '</pre>');
关于javascript - 合并阵列数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36978319/