前端把含有对象的新数组往含有对象老数组里面push,重复的值不要
时间: 2024-05-14 18:13:25 浏览: 76
不重复值操作(很实用)
可以使用forEach方法遍历新数组,然后使用findIndex方法查找老数组中是否已经存在该对象,如果不存在则使用push方法将其添加到老数组中。
代码示例:
```javascript
let oldArray = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 'orange'}];
let newArray = [{id: 2, name: 'banana'}, {id: 4, name: 'grape'}, {id: 5, name: 'watermelon'}];
newArray.forEach(item => {
let index = oldArray.findIndex(oldItem => oldItem.id === item.id);
if (index === -1) {
oldArray.push(item);
}
});
console.log(oldArray); // [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 'orange'}, {id: 4, name: 'grape'}, {id: 5, name: 'watermelon'}]
```
阅读全文