一个数组,根据数组中某个元素,合并数组
// 需要被合并的数组,把Index相同的数组合并 const arr = [{id:0,name:'张三'}, {id:0,name:'李四'}, {id:1,name:'王五'}, {id:1,name:'张伟'}, {id:2,name:'张江'}, ] var map = {}, result = []; for(var i = 0; i < arr.length; i++){ var ai = arr[i]; if(!map[ai.id]){ result.push({ id: ai.id, name: ai.name, data: [ai] }); map[ai.id] = ai; }else{ for(var j = 0; j < result.length; j++){ var dj = result[j]; if(dj.id == ai.id){ dj.data.push(ai); break; } } } } console.log(result) // [{"id":0,"name":"张三","data":[{"id":0,"name":"张三"},{"id":0,"name":"李四"}]}, {"id":1,"name":"王五","data":[{"id":1,"name":"王五"},{"id":1,"name":"张伟"}]}, {"id":2,"name":"张江","data":[{"id":2,"name":"张江"}]}]