我下面有一系列对象
const response =
[
{
id: 105,
label: 'test',
directories: [ '/api/1/directories/500' ]
},
{
id: 337,
label: 'test2',
directories: [ '/api/1/directories/766' ]
},
{
id: 200,
label: 'test20',
directories: [ '/api/1/directories/95' ]
}
]
我有一个名为目录的数组
directories = [ '/api/1/directories/766', '/api/1/directories/95' ]
我正在尝试搜索/过滤响应以仅返回与目录数组中的目录匹配的对象的ID
因此示例输出可能类似于以下内容,这只是匹配对象的ID
sampleOut= [337, 200]
最佳答案
您可以使用reduce
并通过indexOf
检查是否存在
const response =
[
{
id: 105,
label: 'test',
directories: [ '/api/1/directories/500' ]
},
{
id: 337,
label: 'test2',
directories: [ '/api/1/directories/766' ]
},
{
id: 200,
label: 'test20',
directories: [ '/api/1/directories/95' ]
}
]
directories = [ '/api/1/directories/766', '/api/1/directories/95' ];
var result = response.reduce((acc, item)=>{
if(directories.indexOf(item.directories[0]) > -1){
acc.push(item.id);
}
return acc;
},[]);
console.log(result);