[removed] How to remove an array item(JSON object) based on the item property value?

前端 未结 1 715
梦如初夏
梦如初夏 2021-01-07 08:59

like this:

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


        
相关标签:
1条回答
  • 2021-01-07 09:41

    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 讨论(0)
提交回复
热议问题