如何基于给定属性从数组中删除对象

时间:2014-02-11 02:12:44

标签: javascript

我有一个对象数组:

[
  { 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" }
]

如何删除post_id '242'的所有对象?

1 个答案:

答案 0 :(得分:1)

两个步骤:

  1. 向后循环数组
  2. Array.prototype.splice表示匹配属性的索引
  3. 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 })
    }