[英]typescript- filter array of objects based on another array
I have an array of objects like given below 我有如下所示的对象数组
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'
}
];
And I have an array of numbers like given below 我有一个像下面给出的数字数组
let selItems = [0,2,4];
What I'm trying to do is, filter the allItems
array based on selItems
array For doing that, I wrote the following code, which is obviously wrong. 我正在试图做的是,过滤
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);
}
I'm getting the following as output 我得到以下输出
[{
id: 0,
title: "Item 0",
belongsTo: 'admin'
}]
The result I'm expecting is like this: 我期望的结果是这样的:
[
{
id: 0,
title: "Item 0",
belongsTo: 'admin'
},
{
id: 2,
title: "Item 2",
belongsTo: 'all'
},
{
id: 4,
title: "Item 4",
belongsTo: 'all'
}
]
Can anyone show me the right way to do this? 谁能给我示范正确的方法? Thanks!
谢谢!
You might use .map
instead: 您可以改用
.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);
To reduce computational complexity to O(N)
instead of O(N^2)
, you can transform it into an object indexed by id
first: 为了将计算复杂度降低到
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);
Or with filter
: 或使用
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.