如何从数组中删除对象? 我希望从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"}];
当前回答
我做了一个动态函数,以对象数组,键和值,并返回相同的数组后删除所需的对象:
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"));
其他回答
你也可以用一些:
someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
someArray.some(item => {
if(item.name === "Kristian") // Case sensitive, will only remove first instance
someArray.splice(someArray.indexOf(item),1)
})
这就是我用的。
Array.prototype.delete = function(pos){
this[pos] = undefined;
var len = this.length - 1;
for(var a = pos;a < this.length - 1;a++){
this[a] = this[a+1];
}
this.pop();
}
那就像说出来一样简单
var myArray = [1,2,3,4,5,6,7,8,9];
myArray.delete(3);
用任何数字代替3。之后的预期输出应该是:
console.log(myArray); //Expected output 1,2,3,5,6,7,8,9
为简单的数组工作投票给UndercoreJS。
_.without()函数帮助删除一个元素:
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]
ES2015
let someArray = [
{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,58,160"},
{name:"Felix", lines:"1,19,26,96"}
];
someArray = someArray.filter(person => person.name != 'John');
它会除掉约翰!
干净的解决方案是使用Array.filter:
var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; });
问题是它不能在IE < 9上工作。然而,你可以包括来自Javascript库(例如:underscore.js)的代码,为任何浏览器实现这一点。