本文介绍了Javascript:如何根据项目属性值删除数组项目(JSON对象)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
像这样:
var arr = [
{ name: "robin", age: 19 },
{ name: "tom", age: 29 },
{ name: "test", age: 39 }
];
我要删除这样的数组项(数组原型方法):
I want to remove array item like this(an array prototype method):
arr.remove("name", "test"); // remove by name
arr.remove("age", "29"); // remove by age
目前,我是通过这种方法(使用jQuery)做到的:
currently, I do it by this method(use jQuery):
Array.prototype.remove = function(name, value) {
array = this;
var rest = $.grep(this, function(item){
return (item[name] != value);
});
array.length = rest.length;
$.each(rest, function(n, obj) {
array[n] = obj;
});
};
但是我认为该解决方案存在一些性能问题,所以有什么好主意吗?
but I think the solution has some performance issue,so any good idea?
推荐答案
我希望jQuery的名字奇异的grep
表现合理,并在可用的情况下使用Array对象的内置filter
方法,以便可能很好.我要更改的位是将已过滤的项目复制回原始数组的位:
I would hope jQuery's oddly-named grep
would be reasonably performant and use the built-in filter
method of Array objects where available, so that bit is likely to be fine. The bit I'd change is the bit to copy the filtered items back into the original array:
Array.prototype.remove = function(name, value) {
var rest = $.grep(this, function(item){
return (item[name] !== value); // <- You may or may not want strict equality
});
this.length = 0;
this.push.apply(this, rest);
return this; // <- This seems like a jQuery-ish thing to do but is optional
};
这篇关于Javascript:如何根据项目属性值删除数组项目(JSON对象)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!