Arrays 通过id筛选数组,然后通过内部的嵌套数组进行映射
我在尝试访问另一个数组中的嵌套数组时被卡住了,之前我用id对其进行了筛选。很明显,这是我的模拟数据:Arrays 通过id筛选数组,然后通过内部的嵌套数组进行映射,arrays,reactjs,dictionary,filter,Arrays,Reactjs,Dictionary,Filter,我在尝试访问另一个数组中的嵌套数组时被卡住了,之前我用id对其进行了筛选。很明显,这是我的模拟数据: bundleSets: [ { id: 1, title: "bundle set 1", bundles: [ { bundleTitle: "bundl
bundleSets: [
{
id: 1,
title: "bundle set 1",
bundles: [
{
bundleTitle: "bundle 1",
content:[]
},
{
bundleTitle: "bundle 2",
content:[]
}
]
},
{ id:2,
title: "bundle set 2",
bundles: [
{bundleTitle: "ciaopao", content:[]}
]
},
{ id:3,
title: "bundle set 3",
bundles: [
{bundleTitle: "ciapo", content:[]}
]
}
]
现在我需要按id过滤每个bundleSet,然后访问其中的bundles数组并映射这些元素。这就是我试图做的:
const [key,setKey]=useState(1)
const [bundles,setBundles]=useState([])
useEffect(()=>{
const filteredBundles = bundleSets && bundleSets.filter(bundleSet=>bundleSet.id==key).map(filteredBundles=>{
return filteredBundles.bundles
})
setBundles(filteredBundles)
},[key])
现在,如果我尝试映射我在console.log上看到的新状态,就会出现一个奇怪的[Array(1)],而不是通常的[{}],并且我无法将它呈现到页面上。我哪里弄错了?返回一个数组,传递给map
方法的回调返回filteredBundles.bundles
,它是一个数组。所以,你得到了一个数组<顺便说一句,code>filteredBundles是一个容易混淆的名称
由于您正在按id查找捆绑包,并且id在bundleSets
数组中是唯一的,因此可以使用查找按id设置的捆绑包,然后获取捆绑包数组。如果find
返回undefined
(如果找不到键),则可以返回空数组
const bundles=bundleSets?.find(set=>set.id==key)?.bundles | |[]
非常感谢!不客气。