【问题标题】:JS: Filter array of objects by array, when object key is an array of objectsJS:按数组过滤对象数组,当对象键是对象数组时
【发布时间】:2020-09-29 04:24:51
【问题描述】:

我有一个类似于以下内容的对象数组:

let array = [
{
id: 1,
name: Foo,
tools: [{id:3, toolname: Jaw},{id:1, toolname: Law}]
},
{
id: 2,
name: Boo,
tools: [{id:2, toolname: Caw}]
},
{
id: 3,
name: Loo,
tools: [{id:3, toolname: Jaw}, {id:4, toolname: Maw}]
}
]

我正在尝试使用类似于includes 的方法从上述数组中过滤对象,该数组如下所示:

let secondarray = ['Jaw', 'Taw']

如何返回一个对象列表,其中包含在第二个数组中命名的工具?

感谢您的宝贵时间!

【问题讨论】:

    标签: javascript arrays object filter


    【解决方案1】:

    我想你可能会使用这样的东西:

    let array = [
        {
            id: 1,
            name: 'Foo',
            tools: [{ id: 3, toolname: 'Jaw' }, { id: 1, toolname: 'Law' }]
        },
        {
            id: 2,
            name: 'Boo',
            tools: [{ id: 2, toolname: 'Caw' }]
        },
        {
            id: 3,
            name: 'Loo',
            tools: [{ id: 3, toolname: 'Jaw' }, { id: 4, toolname: 'Maw' }]
        }
    ]
    let secondarray = ['Jaw', 'Taw']
    let filteredArray = array.filter(ch => {
        let controlArray = ch.tools.map(t => t.toolname);
        return secondarray.some(t => controlArray.includes(t));
    });
    console.log(filteredArray);
    /**
    which returns 
    
    [ { id: 1, name: 'Foo', tools: [ [Object], [Object] ] },
      { id: 3, name: 'Loo', tools: [ [Object], [Object] ] } ]
    
    */
    

    【讨论】:

    • 这也是一个很好的方法——非常感谢!!
    【解决方案2】:

    您可以在filter() 内使用some() 和tools

    let array = [{id: 1,name: 'Foo',tools: [{id: 3,toolname: 'Jaw'}, {id: 1,toolname: 'Law'}]},{id: 2,name: 'Boo',tools: [{id: 2,toolname: 'Caw'}]},{id: 3,name: 'Loo',tools: [{id: 3,toolname: 'Jaw'}, {id: 4,toolname: 'Maw'}]}]
    let secondarray = ['Jaw', 'Taw']
    
    let filtered = array.filter(item => item.tools.some(obj => secondarray.includes(obj.toolname)))
    
    console.log(filtered)

    【讨论】:

    • 这正是我想要的——简洁明了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 2018-11-12
    • 1970-01-01
    • 2021-08-27
    • 2022-07-20
    • 2019-07-18
    • 2015-11-28
    • 2019-01-04
    相关资源
    最近更新 更多