gpt4 book ai didi

javascript - 如何从嵌套数组中过滤对象

转载 作者:行者123 更新时间:2023-12-02 23:53:54 24 4
gpt4 key购买 nike

我尝试从数组中过滤出空洞对象(objB),该数组与属性的值(titleB2)匹配。

const array = [
{
name: 'objA',
subArray: []
}, {
name: 'objB',
subArray: [
{
title: 'titleB'
}, {
title: 'titleB2'
}, {
title: 'titleB3'
}
]
}, {
name: 'objC',
subArray: [
{
title: 'titleC'
}, {
title: 'titleC2'
}, {
title: 'titleC3'
}
]
}, {
name: 'objD',
subArray: []
}
]

const filterArray = array.filter(a => a.subArray.length > 0);
console.log(filterArray);
// Output: objB + objC

const resArray = filterArray.filter(a => a.subArray.filter(f => f.title === 'titleB2'));
console.log(resArray);
// Output: objB + objC

我想,我做了一些逻辑上错误的事情。但到底是什么?

我需要输出

{
name: 'objB',
subArray: [
{
title: 'titleB'
}, {
title: 'titleB2'
}, {
title: 'titleB3'
}
]
}

我可以想象我使用过滤器 filterArray.filter() 是错误的,因为它已经过滤了?但我这样做是因为一个数组中有多个数组。嗯,说实话,我不太确定。

但我不明白的是,为什么我可以使用条件 a => a.subArray.length > 0? 但不能使用 f => f.title === 'titleB2 '

最佳答案

要在子数组中查找具有特定标题的对象,您可以使用 some()在子数组上,如果子数组中的一项符合您的条件(在本例中为标题),则返回 true:

const array = [{name: 'objA',subArray: []}, {name: 'objB',subArray: [{title: 'titleB'}, {title: 'titleB2'}, {title: 'titleB3'}]}, {name: 'objC',subArray: [{title: 'titleC'}, {title: 'titleC2'}, {title: 'titleC3'}]}, {name: 'objD',subArray: []}]

let found = array.filter(item => item.subArray.some(sub => sub.title === 'titleB2'))
console.log(found)

关于javascript - 如何从嵌套数组中过滤对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55500766/

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