gpt4 book ai didi

javascript - 基于另一个数组从对象数组中过滤数组属性

转载 作者:行者123 更新时间:2023-12-02 22:48:25 27 4
gpt4 key购买 nike

我想根据另一个数组过滤具有数组属性的对象数组:

[
{
id: 50,
name: 'test1',
countries: ['RO','GB'],
}, {
id: 51,
name: 'test2',
countries: ['DE', 'RO'],
}, {
id: 52,
name: 'test3',
countries: ['DE'],
}
]

我想返回一个对象数组,可以通过一组国家/地区进行过滤,这意味着如果我想按 1、2 个国家/地区进行过滤。

1. countries: ['RO']

2. countries: ['RO', 'DE'],

预期输出为:

1.

[
{
id: 50,
name: 'test1',
countries: ['RO', 'DE' ,'GB'],
}, {
id: 51,
name: 'test2',
countries: ['DE', 'RO'],
}
]

2.

[
{
id: 50,
name: 'test1',
countries: ['RO', 'DE' ,'GB'],
}, {
id: 51,
name: 'test2',
countries: ['DE', 'RO'],
}, {
id: 52,
name: 'test3',
countries: ['DE'],
}
]

最佳答案

您可以使用filter()includes()方法;

var import1 = [
{
id: 50,
name: 'test1',
countries: ['RO','GB'],
}, {
id: 51,
name: 'test2',
countries: ['DE', 'RO'],
}, {
id: 52,
name: 'test3',
countries: ['DE'],
}
];

var export1 = import1.filter(function(importz){

return importz.countries.includes("DE");
});

console.log(export1);

关于javascript - 基于另一个数组从对象数组中过滤数组属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58285691/

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