一、根据数组对象中某一key值,合并相同key值的字段,到同一个数组对象中,组成新的数组
1.原数组:
var array = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, age: 25 },
{ id: 3, name: 'Charlie', age: 30 }
];
2.合并后数组:
var array = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie', age: 30 }
];
3.实现方法:
var array = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, age: 25 },
{ id: 3, name: 'Charlie', age: 30 }
];
var mergedArray = array.reduce(function(result, obj) {
var target = result.find(function(item) {
return item.id === obj.id;
});
if (target) {
Object.assign(target, obj);
} else {
result.push(obj);
}
return result;
}, []);
console.log(mergedArray);
4.测试:
二、根据数组对象中某一key值,合并相同key值的对象,到同一个对象中,组成新的数组
1.原数组:
let list = [
{
name: "张三",
gender: "张",
age: "20"
},
{
name: "李四",
gender: "李",
age: "25"
},
{
name: "王五",
gender: "王",
age: "30"
},
{
name: "张飞",
gender: "张",
age: "20"
},
{
name: "李红",
gender: "李",
age: "22"
}
]
2.合并后数组:
let list = [
{
gender: "张",
{
name: "张三",
gender: "张",
age: "20"
},
{
name: "张飞",
gender: "张",
age: "20"
}
},
{
gender: "李",
{
name: "李四",
gender: "李",
age: "25"
},
{
name: "李红",
gender: "李",
age: "22"
}
},
{
gender: "王",
{
name: "王五",
gender: "王",
age: "30"
},
}
]
3.实现方法一:
let tempArr = [];
let Data = [];
for (let i = 0; i < list.length; i++) {
if (tempArr.indexOf(list[i].gender) === -1) {
Data.push({
gender: list[i].gender,
dataInfo: [list[i]]
});
tempArr.push(list[i].gender);
} else {
for (let j = 0; j < Data.length; j++) {
if (Data[j].gender== list[i].gender) {
Data[j].dataInfo.push(list[i]);
break;
}
}
}
}
console.log(Data);
测试:
4.实现方法二:
let dataInfo = {};
list.forEach((item, index) => {
let { gender } = item;
if (!dataInfo[gender]) {
dataInfo[gender] = {
gender,
child: []
}
}
dataInfo[gender].child.push(item);
});
let newList = Object.values(dataInfo);
console.log(newList)
测试: