【发布时间】:2019-10-03 15:54:06
【问题描述】:
我有一个对象数组,如下所示
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'
}
]
谁能告诉我这样做的正确方法? 谢谢!
【问题讨论】:
标签: javascript arrays typescript for-loop