CV工程师
2022-07-19 08:44:39 阅读:803 · 2603 字 · 约 7 分钟
有时,我们可能正在使用具有唯一ID的对象数组,这些ID允许每个对象在其他对象中唯一标识。 例如:
const arr = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Peter' },
{ id: 3, name: 'Kate' },
];
如果我们想从数组中删除具有特定 ID 的对象,该怎么办?在本文中,我们将学习多种方法。
若要在 JavaScript 中按 ID 从数组中删除元素,请使用 findIndex() 方法查找数组中 ID 的对象的索引。然后在数组上调用 splice() 方法,将此索引和 1 作为参数传递,从而在数组中删除对象。例如:
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);
Array.findIndex() 方法返回一个数组中第一个通过回调函数指定的测试的元素的索引。例如:
const arr = [9, 8, 7, 6, 5];
const index = arr.findIndex((num) => num === 7);
console.log(index); // 2
我们指定一个测试,该数组中的一个对象只有在其ID等于指定的ID时才能通过。这使得findIndex()返回具有该ID的对象的索引。
Array.splice()方法通过移除现有元素同时添加新元素来改变数组的内容。
const arr1 = ['a', 'b', 'c'];
// Removing elements
arr1.splice(1, 2);
console.log(arr1); // [ 'a' ]
// Removing and adding new elements
const arr2 = ['a', 'b', 'c'];
arr2.splice(1, 2, 'd', 'e');
console.log(arr2); // [ 'a', 'd', 'e' ]
这个方法需要三个参数:
start - 开始改变数组的索引。deleteCount - 从start开始删除的元素数量item1, item2, ... - 从开始添加到数组中的可变数量的元素。我们指定deleteCount为1,并指定目标索引的开始,以使splice()从数组中只删除具有该索引的对象。我们没有指定任何其他参数,所以没有任何东西被添加到数组中。
Array.splice()方法会改变传递过来的数组。这给我们的 removeObjectWithId() 函数带来了一个副作用。为了避免修改传递过来的数组,我们需要复制一个新的数组并在新的数组上调用splice()。
function removeObjectWithId(arr, id) {
// Making a copy with the Array from() method
const arrCopy = Array.from(arr);
const objWithIdIndex = arrCopy.findIndex((obj) => obj.id === id);
arrCopy.splice(objWithIdIndex, 1);
return arrCopy;
}
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);
// original not modified
/**
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' }
]
*/
console.log(arr);
技巧: 一个函数要尽量避免修改传递过来的参数,一般情况下需要保持传递的参数不变,需要修改时创建一个新的变量进行修改。
我们也可以用filter()方法按ID从数组中移除一个元素。我们在数组上调用filter(),传递一个回调,对数组中除了指定ID的对象以外的每个元素都返回true。
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);
// original not modified
/**
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
{ id: 3, name: 'Peter' }
]
*/
console.log(arr);
Array.filter()方法创建一个新的数组,其中充满了通过回调函数指定的测试的元素。它并不修改原始数组。
const arr = [1, 2, 3, 4];
const filtered = arr.filter((num) => num > 2);
console.log(filtered); // [ 3, 4 ]
在我们的例子中,我们设置了一个测试,只有当数组中的一个对象的id属性不等于指定的ID时才会通过。这保证了具有指定ID的对象不会被包含在从filter()返回的新数组中。
相关阅读
扫描二维码获取文章详情
更多精彩内容尽在:WWW.ZNGG.NET
