gpt4 book ai didi

javascript - 将 Array 与对象数组进行比较并返回匹配对象的一部分

转载 作者:行者123 更新时间:2023-12-03 07:16:49 24 4
gpt4 key购买 nike

下面有一个对象数组

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]

最佳答案

这可以按如下方式完成:

const out = response.filter(o => directories.includes(o.directories[0])).map(o => o.id);

请查看以下可运行的代码片段。

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' ]
}
];

const directories = [ '/api/1/directories/766', '/api/1/directories/95' ];

const out = response.filter(o => directories.includes(o.directories[0])).map(o => o.id);
console.log(out)

关于javascript - 将 Array 与对象数组进行比较并返回匹配对象的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62240845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com