Javascript:如何根据项属性值删除数组项(JSON对象)?

www*_*www 1 javascript jquery

像这样:

var arr = [  
            { name: "robin", age: 19 },   
            { name: "tom", age: 29 },  
            { name: "test", age: 39 } 
          ];  
Run Code Online (Sandbox Code Playgroud)

我想删除像这样的数组项(数组原型方法):

arr.remove("name", "test");  // remove by name  
arr.remove("age", "29");  // remove by age
Run Code Online (Sandbox Code Playgroud)

目前,我通过这种方法(使用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;  
    });  
};  
Run Code Online (Sandbox Code Playgroud)

但我认为解决方案有一些性能问题,所以任何好主意?

Tim*_*own 7

我希望jQuery奇怪的命名grep将是合理的性能并使用filter可用的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
};
Run Code Online (Sandbox Code Playgroud)