js 判断数组对象中是否存在某个对象,如果有替换,没有就添加

// 原数组
let list = [
	{id: 1, name: '张三'},
	{id: 2, name: '李四'},
];
// 需要插入到数组的对象
let newList = {id: 2, name: '王五'};
// 判断数组对象中是否存在该对象
let index = list.findIndex((item) => item.id === newList .id);
// 如果有就替换,没有就添加
if (index !== -1) {
	list.splice(index, 1, newList);
} else {
	list.push(newList);
}
console.log(list);

你可能感兴趣的:(javascript,开发语言,ecmascript)