我有一个对象数组:
[
{ 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'
的所有对象?
答案 0 :(得分:1)
两个步骤:
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 })
}