You need to enable JavaScript to run this app. JavaScript如何从两层结构数组提取生成Summary和class两个新数组
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 21:15:03