【问题标题】:Javascript: How to remove an array item(JSON object) based on the item property value?Javascript:如何根据项目属性值删除数组项目(JSON 对象)?
【发布时间】:2009-12-10 08:25:14
【问题描述】:

像这样:

var arr = [  
            { name: "robin", age: 19 },   
            { name: "tom", age: 29 },  
            { name: "test", age: 39 } 
          ];  

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

arr.remove("name", "test");  // remove by name  
arr.remove("age", "29");  // remove by age

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

但我认为该解决方案存在一些性能问题,所以有什么好主意吗?

【问题讨论】:

  • 这与 JSON 没有任何关系。
  • 如果答案解决了您的问题,请点击旁边的复选标记。谢谢。

标签: javascript jquery


【解决方案1】:

我希望 jQuery 的奇怪名称 grep 将具有合理的性能,并在可用的情况下使用 Array 对象的内置 filter 方法,因此该位可能没问题。我要更改的一点是将过滤后的项目复制回原始数组:

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
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-11
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多