如何从数组中删除对象? 我希望从someArray中删除包含名称Kristian的对象。例如:
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
我想实现:
someArray = [{name:"John", lines:"1,19,26,96"}];
如何从数组中删除对象? 我希望从someArray中删除包含名称Kristian的对象。例如:
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
我想实现:
someArray = [{name:"John", lines:"1,19,26,96"}];
当前回答
虽然这可能不适合这种情况,我发现前几天,如果你不需要改变数组的大小,你也可以使用delete关键字从数组中删除一个项目。
var myArray = [1,2,3];
delete myArray[1];
console.log(myArray[1]); //undefined
console.log(myArray.length); //3 - doesn't actually shrink the array down
其他回答
这个怎么样?
$.each(someArray, function(i){
if(someArray[i].name === 'Kristian') {
someArray.splice(i,1);
return false;
}
});
最简单的解决方案是创建一个映射,按名称存储每个对象的索引,如下所示:
//adding to array
var newPerson = {name:"Kristian", lines:"2,5,10"}
someMap[ newPerson.name ] = someArray.length;
someArray.push( newPerson );
//deleting from the array
var index = someMap[ 'Kristian' ];
someArray.splice( index, 1 );
const someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
我们得到对象的索引它的name属性值为"Kristian"
const index = someArray.findIndex(key => key.name === "Kristian");
console.log(index); // 0
通过使用拼接函数我们删除了name属性值为“Kristian”的对象
someArray.splice(index,1);
console.log(someArray); // [{name:"John", lines:"1,19,26,96"}]
我做了一个动态函数,以对象数组,键和值,并返回相同的数组后删除所需的对象:
function removeFunction (myObjects,prop,valu)
{
return myObjects.filter(function (val) {
return val[prop] !== valu;
});
}
完整示例:DEMO
var obj = {
"results": [
{
"id": "460",
"name": "Widget 1",
"loc": "Shed"
}, {
"id": "461",
"name": "Widget 2",
"loc": "Kitchen"
}, {
"id": "462",
"name": "Widget 3",
"loc": "bath"
}
]
};
function removeFunction (myObjects,prop,valu)
{
return myObjects.filter(function (val) {
return val[prop] !== valu;
});
}
console.log(removeFunction(obj.results,"id","460"));
在数组上使用splice函数。指定开始元素的位置和要删除的子序列的长度。
someArray.splice(pos, 1);