最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript: How to remove an array item(JSON object) based on the item property value? - Stack Overflow

programmeradmin3浏览0评论

like this:

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

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?

like this:

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

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?

Share Improve this question edited Dec 10, 2009 at 15:01 Jeremy Stein 19.7k18 gold badges70 silver badges83 bronze badges asked Dec 10, 2009 at 8:25 wwwwww 4,1257 gold badges32 silver badges27 bronze badges 1
  • This doesn't really have anything to do with JSON. – Tim Down Commented Dec 10, 2009 at 10:10
Add a ment  | 

1 Answer 1

Reset to default 7

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
};
发布评论

评论列表(0)

  1. 暂无评论