JavaScript如何从两层结构数组提取生成Summary和class两个新数组
解决方案
首先明确:使用forEach或者while循环配合push的实现思路完全正确,没有拿到预期结果的核心原因大概率是取值时跳过了attributes层级,没有正确访问到目标属性。
1. forEach 实现示例
// 原始数组 const sourceArr = [ { "attributes": { "Summary": 10, "class": "Blue" } }, { "attributes": { "Summary": 63, "class":"Red" } } ]; const summaryList = []; const classList = []; sourceArr.forEach(item => { // 先访问attributes层级,再取对应属性值 summaryList.push(item.attributes.Summary); classList.push(item.attributes.class); }); // 执行结果:summaryList = [10, 63],classList = ["Blue", "Red"]
2. while 循环实现示例
const sourceArr = [ { "attributes": { "Summary": 10, "class": "Blue" } }, { "attributes": { "Summary": 63, "class":"Red" } } ]; const summaryList = []; const classList = []; let i = 0; while(i < sourceArr.length) { const currentItem = sourceArr[i]; summaryList.push(currentItem.attributes.Summary); classList.push(currentItem.attributes.class); i++; }
两种实现最终拿到的结果完全一致。
内容的提问来源于stack exchange,提问作者WhaleShark
相关产品推荐
相关产品推荐

