对象数组的合并和去重
程序员文章站
2024-01-03 17:46:34
...
前提:默认对象中name为主键,即对象有相同name则需要合并为一个对象,且属性合并。
两种方法:原理版(Method 1) 和 精简版(Method 2),直接上代码。
- Method 1
var songs = [
{name:"李健",artist:"风吹麦浪",address:"春晚"},
{name:"晴天",artist:"周杰伦",tag:"R&B"},
{artist:"周杰伦",name:"晴天"}
];
var arr = [
{name:"羽根",artist:"air"},
{name:"晴天",artist:"周杰伦"}
]
for (let i = 0; i < arr.length; i++) {
songs.push(arr[i])
}
console.log('songs:', songs);
function unique(songs){
let result = {};
let finalResult=[];
for(let i=0;i<songs.length;i++){
result[songs[i].name]=Object.assign(result[songs[i].name]?result[songs[i].name]:{}, songs[i]);
}
console.log('result:', result);
for(item in result){
finalResult.push(result[item]);
}
console.log('finalResult:', finalResult);
return finalResult;
}
console.log('unique:', unique(songs));
- Method 2
var songs = [
{name:"李健",artist:"风吹麦浪",address:"春晚"},
{name:"晴天",artist:"周杰伦",tag:"R&B"},
{artist:"周杰伦",name:"晴天"}
];
var arr = [
{name:"羽根",artist:"air"},
{name:"晴天",artist:"周杰伦"}
]
this.songs = this.songs.concat(this.arr)
console.log('songs:', songs);
function unique2(arr) {
const res = new Map();
return arr.filter((arr) => !res.has(arr.name) && res.set(arr.name, 1))
}
console.log('unique2:', unique2(songs));