[英]typescript- filter array of objects based on another array
我有如下所示的對象數組
readonly allItems = [
{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 1,
title: "Item 1",
belongsTo: 'user'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 3,
title: "Item 3",
belongsTo: 'user'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
];
我有一個像下面給出的數字數組
let selItems = [0,2,4];
我正在試圖做的是,過濾allItems
基於陣列selItems
陣列做這件事,我寫了下面的代碼,這顯然是錯誤的。
for(let i=0; i< this.allItems.length; i++){
if(selItems.includes(this.allItems[i].id)){
tempMenu.push(this.allItems[i]);
}
console.log(tempMenu);
}
我得到以下輸出
[{
id: 0,
title: "Item 0",
belongsTo: 'admin'
}]
我期望的結果是這樣的:
[
{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
]
誰能給我示范正確的方法? 謝謝!
您可以改用.map
:
const allItems = [{ id: 0, title: "Item 0", belongsTo: 'admin' }, { id: 1, title: "Item 1", belongsTo: 'user' }, { id: 2, title: "Item 2", belongsTo: 'all' }, { id: 3, title: "Item 3", belongsTo: 'user' }, { id: 4, title: "Item 4", belongsTo: 'all' } ]; const selItems = [0, 2, 4]; const output = selItems.map(num => allItems.find(({ id }) => id === num)); console.log(output);
為了將計算復雜度降低到O(N)
而不是O(N^2)
,可以將其轉換為首先由id
索引的對象:
const allItems = [{ id: 0, title: "Item 0", belongsTo: 'admin' }, { id: 1, title: "Item 1", belongsTo: 'user' }, { id: 2, title: "Item 2", belongsTo: 'all' }, { id: 3, title: "Item 3", belongsTo: 'user' }, { id: 4, title: "Item 4", belongsTo: 'all' } ]; const selItems = [0, 2, 4]; const allItemsById = allItems.reduce((a, item) => { a[item.id] = item; return a; }, {}); const output = selItems.map(num => allItemsById[num]); console.log(output);
或使用filter
:
const allItems = [{ id: 0, title: "Item 0", belongsTo: 'admin' }, { id: 1, title: "Item 1", belongsTo: 'user' }, { id: 2, title: "Item 2", belongsTo: 'all' }, { id: 3, title: "Item 3", belongsTo: 'user' }, { id: 4, title: "Item 4", belongsTo: 'all' } ]; const selItemsSet = new Set([0, 2, 4]); const output = allItems.filter(({ id }) => selItemsSet.has(id)); console.log(output);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.