如何使用 JavaScript 从数组中删除对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3396088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I remove an object from an array with JavaScript?
提问by mavera
I have an JavaScript object like this:
我有一个这样的 JavaScript 对象:
id="1";
name = "serdar";
and I have an Array which contains many objects of above. How can I remove an object from that array such as like that:
我有一个包含上述许多对象的数组。如何从该数组中删除一个对象,例如:
obj[1].remove();
回答by BGerrissen
Well spliceworks:
很好的splice作品:
var arr = [{id:1,name:'serdar'}];
arr.splice(0,1);
// []
Do NOT use the deleteoperator on Arrays.
不要delete在数组上使用运算符。
But maybe you want something like this?
但也许你想要这样的东西?
var removeByAttr = function(arr, attr, value){
var i = arr.length;
while(i--){
if( arr[i]
&& arr[i].hasOwnProperty(attr)
&& (arguments.length > 2 && arr[i][attr] === value ) ){
arr.splice(i,1);
}
}
return arr;
}
Just an example below.
下面只是一个例子。
var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];
removeByAttr(arr, 'id', 1);
// [{id:2,name:'alfalfa'}, {id:3,name:'joe'}]
removeByAttr(arr, 'name', 'joe');
// [{id:2,name:'alfalfa'}]
回答by Benjamin S. Leveritt
If you have access to ES2015 functions, and you're looking for a more functional approach I'd go with something like:
如果您可以访问 ES2015 函数,并且正在寻找一种更实用的方法,我会采用以下方法:
const people = [
{ id: 1, name: 'serdar' },
{ id: 5, name: 'alex' },
{ id: 300, name: 'brittany' }
];
const idToRemove = 5;
const filteredPeople = people.filter((item) => item.id !== idToRemove);
// [
// { id: 1, name: 'serdar' },
// { id: 300, name: 'brittany' }
// [
Watch out though, filter()is non-mutating, so you'll get a new array back.
不过要注意,filter()它是非变异的,所以你会得到一个新的数组。
回答by Daniel Vassallo
You can use either the splice()method or the deleteoperator.
The main difference is that when you delete an array element using the deleteoperator, the length of the array is not affected, even if you delete the last element of the array. On the other hand, the splice()method shifts all the elements such that no holes remain in the place of the deleted element.
主要区别在于,使用delete运算符删除数组元素时,即使删除数组的最后一个元素,也不影响数组的长度。另一方面,该splice()方法移动所有元素,使得在被删除元素的位置上没有空洞。
Example using the deleteoperator:
使用delete运算符的示例:
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
if (3 in trees) {
// this does not get executed
}
console.log(trees.length); // 5
console.log(trees); // ["redwood", "bay", "cedar", undefined, "maple"]
Example using the splice()method:
使用该splice()方法的示例:
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
trees.splice(3, 1);
console.log(trees.length); // 4
console.log(trees); // ["redwood", "bay", "cedar", "maple"]
回答by Six Foot Three Foot
I use this quite a bit so I created a small prototype. Simply looks for the item then pulls it out if there is a match.
我经常使用它,所以我创建了一个小原型。只需查找该项目,然后在匹配时将其拉出即可。
//Prototype to remove object from array, removes first
//matching object only
Array.prototype.remove = function (v) {
if (this.indexOf(v) != -1) {
this.splice(this.indexOf(v), 1);
return true;
}
return false;
}
Can be called like:
可以这样调用:
var arr = [12, 34, 56];
arr.remove(34);
The result would be [12, 56]
结果将是 [12, 56]
Has a boolean return if there was a successful remove, false if the element didn't exist.
如果删除成功则返回布尔值,如果元素不存在则返回 false。
回答by Marcelo
If you know the index that the object has within the array then you can use splice(), as others have mentioned, ie:
如果您知道对象在数组中的索引,那么您可以使用 splice(),正如其他人所提到的,即:
var removedObject = myArray.splice(index,1);
removedObject = null;
If you don't know the index then you need to search the array for it, ie:
如果您不知道索引,则需要在数组中搜索它,即:
for (var n = 0 ; n < myArray.length ; n++) {
if (myArray[n].name == 'serdar') {
var removedObject = myArray.splice(n,1);
removedObject = null;
break;
}
}
Marcelo
马塞洛
回答by Manoj Yadav
var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];
var ind = arr.findIndex(function(element){
return element.id===2;
})
if(ind!==-1){
arr.splice(ind, 1)
}
console.log (arr)
Please note that findIndex method is not supported in Internet Explorer but polyfill can be used from here
请注意,Internet Explorer 不支持 findIndex 方法,但可以从此处使用 polyfill
回答by James V. Fields
//K.I.S.S. method
//(the setup/comments is/are longer than the code)
//cards is a two dimensional array object
// has an array object with 4 elements at each first dimensional index
//var cards = new Array()
//cards[cards.length] = new Array(name, colors, cost, type)
//Can be constructed with Associated arrays, modify code as needed.
//my test array has 60 'cards' in it
// 15 'cards' repeated 4 times each
// groups were not sorted prior to execution
// (I had 4 groups starting with 'U' before the first 'A')
//Should work with any dimensionality as long as first
//index controls sort order
//sort and remove duplicates
//Algorithm:
// While same name side by side, remove higher entry;
// assumes 'cards' with same name have same other data
// (otherwise use cards[i-1] === cards[i] to compare array objects).
//Tested on IE9 and FireFox (multiple version #s from 31 up).
//Also tested by importing array data from 5MB text file.
//Quick execution
cards.sort()
for (i=1; i<cards.length-1; i++){
while (cards[i-1][0] == cards[i][0]){
cards.splice(i,1)
}
}
回答by Quentin
回答by Stefan Hoth
Use delete-keyword.
使用删除关键字。
delete obj[1];
EDIT: see: Deleting array elements in JavaScript - delete vs splicedelete will undefine the offset but not completly remove the entry. Splice would be correct like David said.
编辑:请参阅:在 JavaScript 中删除数组元素 - 删除与拼接删除将取消定义偏移量但不会完全删除条目。拼接是正确的,就像大卫说的那样。
回答by Tomalak
delete obj[1];
Note that this will not change array indices. Any array members you delete will remain as "slots" that contain undefined.
请注意,这不会更改数组索引。您删除的任何数组成员将保留为包含undefined.

