【问题标题】:Find some by array of ids dynamically通过 id 数组动态查找一些
【发布时间】:2020-10-22 05:55:40
【问题描述】:

这是一个代码示例:-

projects数组:-

let projects = [
    {
        id: 1,
        name: 'Project 1',
        techs: [
            { id: 1a, name: 'Tech 1' }, { id: 1b, name: 'Tech 2' }
        ]
    },
    {
        id: 2,
        name: 'Project 2',
        techs: [
            { id: 1b, name: 'Tech 2' }, { id: 1c, name: 'Tech 3' }
        ]
    },
    {
        id: 3,
        name: 'Project 3',
        techs: [
            { id: 1c, name: 'Tech 3' }, { id: 1d, name: 'Tech 4' }
        ]
    },
    {
        id: 4,
        name: 'Project 4',
        techs: [
            { id: 1d, name: 'Tech 1' }, { id: 1e, name: 'Tech 5' }
        ]
    }
]

现在我的代码如下所示:-

// get projects that have tech of ids of '1a' and '1d'
let filteredProjs = projects.filter(proj => proj.techs.some(tech => tech.id === '1a' || tech.id === '1d'))

console.log(filteredProjs) // Will give me 'Project 1', 'Project 3', and 'Project 4'

它有效。但是我怎样才能使它变得更加动态,而不必手动插入一些condition? (例如:tech.id === '1a' || tech.id === '1d'

【问题讨论】:

    标签: arrays sorting arraylist filter array-filter


    【解决方案1】:

    您可以使用要查找的技术数组,然后根据该数组是否包含当前的tech.id 值进行过滤:

    // get projects that have tech of ids of '1a' and '1d'
    let techs = ['1a', '1d'];
    let filteredProjs = projects.filter(proj => proj.techs.some(tech => techs.includes(tech.id)));
    

    let projects = [
        {
            id: 1,
            name: 'Project 1',
            techs: [
                { id: '1a', name: 'Tech 1' }, { id: '1b', name: 'Tech 2' }
            ]
        },
        {
            id: 2,
            name: 'Project 2',
            techs: [
                { id: '1b', name: 'Tech 2' }, { id: '1c', name: 'Tech 3' }
            ]
        },
        {
            id: 3,
            name: 'Project 3',
            techs: [
                { id: '1c', name: 'Tech 3' }, { id: '1d', name: 'Tech 4' }
            ]
        },
        {
            id: 4,
            name: 'Project 4',
            techs: [
                { id: '1d', name: 'Tech 1' }, { id: '1e', name: 'Tech 5' }
            ]
        }
    ]
    
    // get projects that have tech of ids of '1a' and '1d'
    let techs = ['1a', '1d'];
    let filteredProjs = projects.filter(proj => proj.techs.some(tech => techs.includes(tech.id)));
    
    console.log(filteredProjs)

    【讨论】:

    • 我怎么想不到呢?谢谢!
    • @lala 有时只需要其他人查看代码。我很高兴能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 2019-08-16
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 2018-10-12
    相关资源
    最近更新 更多