1. 程式人生 > >數組合並物件裡相同屬性值

數組合並物件裡相同屬性值

var arr = [
{
"id": 1,
"name": 'zengzhi',
"age": 25
},
{
"id": 1,
"name": 'longlu',
"age": 20
},
{
"id": 2,
"name": 'zengzhi2',
"age": 25
},
];

/*var arr = [
{
"id": 1,
"info": [
{
"name": 'zengzhi',
"age": 25
},
{
"name": 'longlu',
"age": 20
}
]

}
{
"id": 2,
"name": 'zengzhi2',
"age": 25
},
];*/


var listArr = [];

arr.forEach((el,index) => {
for(var i = 0; i < listArr.length; i++){
if(listArr[i].id == el.id){
listArr[i].listInfo.push({
name:el.name,
age: el.age
});
return;
}

}
listArr.push({
id:el.id,
listInfo: [{
name:el.name,
age: el.age
}]
})
})
console.log(listArr);