Javascript 如何基于给定属性从数组中删除对象
我有一个对象数组:Javascript 如何基于给定属性从数组中删除对象,javascript,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" } ] 如何删除具有'242'的post\u id的所有对象?两个步骤: 向后循
[
{ 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\u id
的所有对象?两个步骤:
以下是在javascript中从数组中删除元素的几种方法:
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
}
function removeObjectsWithPostId (arr, id) {
return arr.filter(function (obj) { return obj.post_id !== id })
}