JavaScript 从数组构建数组

Wha*_*ark 1 javascript

我目前有一个有 2 个级别的数组。我试图从初始数组构建两个新数组,但似乎坚持使用的方法。我尝试了 forEach()、while 循环以及 push 都无济于事。

我当前的数组结构:

[
  {
    "attributes": {
      "Summary": 10,
      "class": "Blue"
    }
  },
  {
    "attributes": {
      "Summary": 63,
      "class":"Red"
    }
  }
]
Run Code Online (Sandbox Code Playgroud)

我希望构建两个数组,一个用于汇总值,另一个用于类值。

我的 forEach 或 while 循环方法是否在正确的路径上?

gus*_*afc 5

如果您有一个数组并想将其转换为另一个数组,最简单的方法是使用map(它基本上创建一个包含通过函数运行每个元素的结果的新数组):

const arr = [
  {
    "attributes": {
      "Summary": 10,
      "class": "Blue"
    }
  },
  {
    "attributes": {
      "Summary": 63,
      "class":"Red"
    }
  }
];
const summaries = arr.map(e => e.attributes.Summary);
const classes = arr.map(e => e.attributes.class);

Run Code Online (Sandbox Code Playgroud)