我有一个像这样的JavaScript对象:
id="1";
name = "serdar";
我有一个包含上面许多对象的数组。我如何从该数组中删除一个对象,例如:
obj[1].remove();
Answers:
效果不错splice
:
var arr = [{id:1,name:'serdar'}];
arr.splice(0,1);
// []
不要delete
在数组上使用运算符。delete
不会从Array中删除条目,只会将其替换为undefined
。
var arr = [0,1,2];
delete arr[1];
// [0, undefined, 2]
但是也许您想要这样的东西?
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;
}
下面只是一个例子。
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'}]
如果您有权使用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' }
// [
请注意,filter()
它是非变异的,因此您将获得一个新的数组。
主要区别在于,使用delete
运算符删除数组元素时,即使删除数组的最后一个元素,数组的长度也不会受到影响。另一方面,该splice()
方法移动所有元素,以使没有孔留在已删除元素的位置。
使用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"]
使用splice()
方法的示例:
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
trees.splice(3, 1);
console.log(trees.length); // 4
console.log(trees); // ["redwood", "bay", "cedar", "maple"]
我使用了很多,所以我创建了一个小原型。只需查找项目,然后找到匹配项即可将其取出。
//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;
}
可以这样称呼:
var arr = [12, 34, 56];
arr.remove(34);
结果将是[12,56]
如果删除成功,则返回布尔值;如果该元素不存在,则返回false。
如果您知道对象在数组中的索引,则可以使用splice(),就像其他人提到的那样,即:
var removedObject = myArray.splice(index,1);
removedObject = null;
如果您不知道索引,则需要在数组中搜索它,即:
for (var n = 0 ; n < myArray.length ; n++) {
if (myArray[n].name == 'serdar') {
var removedObject = myArray.splice(n,1);
removedObject = null;
break;
}
}
马塞洛
//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)
}
}
delete
将取消定义偏移量但不会完全删除”-这并不完全正确,因为delete
将完全删除元素,如if (3 in trees)
我的答案中的测试所示。唯一的事情是它不会移动其他元素来填充孔,因此长度不会受到影响。因此,如果显示数组,您将得到undefined
哪里有洞....
delete
与将元素设置为并不相同undefined
。这也解释了这里:developer.mozilla.org/en/Core_JavaScript_1.5_Reference/...
var apps = [{{id:34,name:'My App',another:'thing'},{id:37,name:'My New App',other:'things']];
//获取ID为37的对象的索引
var removeIndex = apps.map(function(item){return item.id;})。indexOf(37);
//删除对象
apps.splice(removeIndex,1);
我们有一个对象数组,我们只想使用id属性删除一个对象
var apps = [
{id:34,name:'My App',another:'thing'},
{id:37,name:'My New App',another:'things'
}];
获取ID为37的对象的索引
var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);
// remove object
apps.splice(removeIndex, 1);