第一种:使用filter()
方法的方式。这种方法通过传入一个回调函数来过滤出不包含特定ID的对象,从而创建一个新的数组。
function removeObjectWithId(arr, id) {
return arr.filter((obj) => obj.id !== id);
}
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' },
];
const newArr = removeObjectWithId(arr, 2);
// 输出: [ { id: 1, name: 'John' }, { id: 3, name: 'Peter' } ]
console.log(newArr);
// 原始数组未被修改
console.log(arr);
第二种:使用findIndex()
和splice()
方法的方式。这种方法首先使用findIndex()
方法找到具有特定ID的对象的索引,然后使用splice()
方法从数组中删除该对象
function removeObjectWithId(arr, id) {
const objWithIdIndex = arr.findIndex((obj) => obj.id === id);
arr.splice(objWithIdIndex, 1);
return arr;
}
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' },
];
removeObjectWithId(arr, 2);
// 输出: [ { id: 1, name: 'John' }, { id: 3, name: 'Peter' } ]
console.log(arr);
第三种:使用forEach()
方法和临时数组来删除特定项
function removeObjectWithId(arr, id) {
const newArr = [];
arr.forEach((obj) => {
if (obj.id !== id) {
newArr.push(obj);
}
});
return newArr;
}
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' },
];
const newArr = removeObjectWithId(arr, 2);
// 输出: [ { id: 1, name: 'John' }, { id: 3, name: 'Peter' } ]
console.log(newArr);
// 原始数组未被修改
console.log(arr);
第四中:使用reduce()
方法来删除特定项
function removeObjectWithId(arr, id) {
return arr.reduce((acc, obj) => {
if (obj.id !== id) {
acc.push(obj);
}
return acc;
}, []);
}
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' },
];
const newArr = removeObjectWithId(arr, 2);
// 输出: [ { id: 1, name: 'John' }, { id: 3, name: 'Peter' } ]
console.log(newArr);
// 原始数组未被修改
console.log(arr);