我有一个如下所示的对象数组
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];
我想做的是,根据 selItems
数组过滤 allItems
数组
为此,我编写了以下代码,这显然是错误的。
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);
关于javascript - typescript -基于另一个数组过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56167380/