2014-02-11 47 views
-2

刪除對象我有對象的數組:如何從一個陣列基於給定屬性

[ 
    { content: "lelzz", post_id: "241" }, 
    { content: "zzyzz", post_id: "242" }, 
    { content: "abcde", post_id: "242" }, 
    { content: "12345", post_id: "242" }, 
    { content: "nomno", post_id: "243" } 
] 

如何刪除與'242'一個post_id所有對象?

+0

以下是一些在javascript中從數組中刪除元素的方法:http://stackoverflow.com/questions/10024866/remove-object-from-array-using-javascript – rob

回答

1

兩個步驟:

  1. 遍歷數組倒退
  2. Array.prototype.splice與匹配性質指標
function removeObjectsWithPostId (arr, id) { 
    for (var i = arr.length - 1; i > -1; i--) { 
     if (arr[i].post_id === id) arr.splice(i, 1) 
    } 
    return arr 
} 

如果你知道,有可能與多個對象這個屬性,你應該更喜歡Array.prototype.filter

function removeObjectsWithPostId (arr, id) { 
    return arr.filter(function (obj) { return obj.post_id !== id }) 
}