使用嵌套对象解构访问API返回数据中ArticleList数组输出undefined问题
问题原因
你代码里有两处明显错误导致输出undefined:
- 你没有调用
makeArrayOfArticleList函数,直接对函数本身做解构,无法拿到返回的JSON数据 FinalCombinationList是数组类型,不是对象,数组内部的每个元素才包含ArticleList属性,不能直接从数组上解构ArticleList
修正方案
如果要获取所有ArticleList的内容,可以参考如下代码:
function makeArrayOfArticleList() { return { data: { FinalHelperCombinationList: [], FinalCombinationList: [ { ArticleList: [ { Id: 54, Description: "VT-U 20mm/4x10-20/140(30)", Number: "719241", Datasheet: "04.06-01_vt-u.pdf", }, { Id: 54, Description: "VT-U 20mm/4x10-20/140(30)", Number: "719241", Datasheet: "04.06-01_vt-u.pdf", }, ], TotalSize: 40, HighSize: 40, Category1: false, Category2: false, Category3: false, Category4: false, Category6: false, Category7: false, CombinationScore: 0, }, { ArticleList: [ { Id: 113, Description: "VT-U 30mm/4x10-20/140(24)", Number: "719230", Datasheet: "04.06-01_vt-u.pdf", }, { Id: 114, Description: "VT-U 10mm/4x10-20/140(40)", Number: "719240", Datasheet: "04.06-01_vt-u.pdf", }, ], TotalSize: 40, HighSize: 40, Category1: false, Category2: false, Category3: false, Category4: false, Category6: false, Category7: false, CombinationScore: 0, }, { ArticleList: [ { Id: 51, Description: "VT-B 15mm/4x10-15/140, 4Stege(40)", Number: "719041", Datasheet: "04.05-01_vt-b.pdf", }, { Id: 51, Description: "VT-B 15mm/4x10-15/140, 4Stege(40)", Number: "719041", Datasheet: "04.05-01_vt-b.pdf", }, { Id: 114, Description: "VT-U 10mm/4x10-20/140(40)", Number: "719240", Datasheet: "04.06-01_vt-u.pdf", }, ], TotalSize: 40, HighSize: 40, Category1: false, Category2: false, Category3: false, Category4: false, Category6: false, Category7: false, CombinationScore: 0, }, ], }, }; } // 1. 先调用函数拿到返回数据 const result = makeArrayOfArticleList(); // 2. 解构出FinalCombinationList数组 const { data: { FinalCombinationList } } = result; // 3. 遍历数组收集所有ArticleList,或者按需取对应下标的ArticleList // 示例:收集所有ArticleList到一个数组中 const allArticleList = FinalCombinationList.flatMap(item => item.ArticleList); console.log(allArticleList);
如果只需要取某个特定位置的ArticleList,比如第一个元素的,直接用FinalCombinationList[0].ArticleList即可。
内容的提问来源于stack exchange,提问作者wwEr1k
相关产品推荐
相关产品推荐

