JavaScript如何获取JSON结构中嵌套的内层数组数据?
问题核心原因
b.artifacts 是数组类型,不是对象类型,数组本身没有 techBasedArtifacts 这个属性,该属性属于数组内部的每个元素对象,所以直接访问 b.artifacts.techBasedArtifacts 会返回undefined。
正确访问方式
你可以根据需求选择对应的访问逻辑:
- 访问指定下标元素的内层数组,比如取第一个技术分类对应的嵌套数组:
// 取下标为0的元素的techBasedArtifacts属性 console.log(b.artifacts[0].techBasedArtifacts) // 输出:[{title: "Agile 1", artifactLink: "https://www.google.com/"}, {title: "Agile 2", artifactLink: "https://www.google.com/"}]
- 遍历所有外层数组元素,批量获取所有内层数组内容:
b.artifacts.forEach(item => { console.log(`技术分类:${item.technology} 对应的工件列表:`, item.techBasedArtifacts) })
- 如果需要把所有内层数组合并成一个一维数组,可以用flatMap实现:
const allArtifacts = b.artifacts.flatMap(item => item.techBasedArtifacts) console.log(allArtifacts)
内容的提问来源于stack exchange,提问作者Venkat Sai
相关产品推荐
相关产品推荐

