let obj1 = [
{id:1,name:'a1'},
{id:2,name:'a2'},
{id:3,name:'a3'},
{id:4,name:'a4'},
{id:5,name:'a6'},
{id:6,name:'a1'},
{id:7,name:'a2'},
{id:8,name:'a3'},
{id:9,name:'a4'}
];
let obj2 = [
{id:1,age:'1'},
{id:4,age:'4'},
{id:3,age:'3'},
{id:2,age:'2'},
{id:9,age:'9'},
{id:8,age:'8'},
{id:7,age:'7'},
{id:6,age:'6'},
{id:5,age:'5'}
]
之前的方法
/**之前常用的方法*/
let newObj = []
obj1.forEach(item=>{
obj2.forEach(list=>{
if(item.id === list.id){
newObj.push(Object.assgin(item,list))
}
})
})
console.log(newObj)
/*{id: 1, name: 'a1', age: '1'}
{id: 2, name: 'a2', age: '2'}
{id: 3, name: 'a3', age: '3'}
{id: 4, name: 'a4', age: '4'}
{id: 5, name: 'a6', age: '5'}
{id: 6, name: 'a1', age: '6'}
{id: 7, name: 'a2', age: '7'}
{id: 8, name: 'a3', age: '8'}
{id: 9, name: 'a4', age: '9'}*/
通过forEach循环便利判断id是否相等,相等就使用Object.assgin()方法拼接对象。虽然能实现效果,但是性能不好,9条数据就是81次循环,浪费性能。
解决方案
可以通过数据结构上,声明一个对象,先遍历obj1,属性为obj1每条数据的id值,值为obj1的每条数据存在新对象里。再遍历obj2,通过id获取新对象的属性直接拼接数据即可,这样减少循环次数变成 9+9而不是9*9了,代码如下
let newObj = {}, newArr = [];
obj1.forEach(item=>{
newObj[item.id] = item
})
obj2.forEach(item=>{
newArr.push(Object.assign(newObj[item.id],item))
})
console.log(newArr)
Object.assign() :ES6提供的操作对象的API,主要用于合并多个对象,
语法:Object,assign(obj1,obj2) ,返回新的对象,不修改原对象
如果obj1和obj2中有属性名相同,则obj2里的值会覆盖obj1里面的值(即后面的值会覆盖前面的值)
forEach() :foreach遍历接受三个参数
语法:arr.forEach((item,index,arr)=>{})
item:每一条数据(必传),index:下标,选传;arr:数组本身,选传;
注意:forEach()终止循环要用try catch
try {
let array = ["第一","第二","第三","第四"];
array.forEach(item=>{
if(item=='第三'){
throw new Error('第三')
}
console.log(item)
})
} catch (error) {
if(error.message!="第三") throw error;
}
网友评论