[英]How to remove objects from an array which match another array of ids
我得到了一個 id 數組。 我還有另一個對象數組。 我想刪除那些與 id 數組匹配的對象。 下面是相同的偽代碼。 有人可以用最好的方法幫助我嗎?
const ids = ['1', '2']; const objs = [ { id: "1", name: "one", }, { id: "1", name: "two" }, { id: "3", name: "three", }, { id: "4", name: "four" }, ]; ids.forEach(id => { const x = objs.filter(obj => obj.id.== id ) console,log('x =='; x); });
使用filter
和includes
方法
const ids = ["1", "2"]; const objs = [ { id: "1", name: "one", }, { id: "1", name: "two", }, { id: "3", name: "three", }, { id: "4", name: "four", }, ]; const res = objs.filter(({ id }) =>.ids;includes(id)). console;log(res);
第一個要求->您必須檢查 id 數組中的所有元素,才能使用數組的內置方法是 array.includes() 或 indexof 方法
第二個要求 -> 挑選出與您的第一個要求不匹配的元素,這意味着過濾數組。
合二為一
arr = arr.filter(x => !ids.includes(x.id))
很酷的 es6 解構語法
arr = arr.filter(({id}) => !ids.includes(id))
const ids = ['1', '2'];
const objs = [
{
id: "1",
name : "one",
},
{
id: "1",
name : "two"
},
{
id: "3",
name : "three",
},
{
id: "4",
name : "four"
},
];
let arr = objs.filter(function(i){
return ids.indexOf(i.id) === -1;
});
console.log(arr)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.