2009-12-10 79 views
1

這樣的:Javascript:如何根據項目屬性值刪除數組項目(JSON對象)?

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

但我認爲解決方案有一些性能問題,所以有什麼好主意?

+0

這實際上與JSON沒有任何關係。 – 2009-12-10 10:10:48

+0

如果答案解決了您的問題,請點擊旁邊的複選標記。謝謝。 – 2009-12-10 15:00:43

回答

7

我希望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 
}; 
+0

非常感謝。 – www 2009-12-10 11:15:25

相關問題