JavaScript从数组构建数组

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

我当前的数组结构:

[
  {
    "attributes": {
      "Summary": 10,
      "class": "Blue"
    }
  },
  {
    "attributes": {
      "Summary": 63,
      "class":"Red"
    }
  }
]

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

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

回答

如果您有一个数组并想将其转换为另一个数组,最简单的方法是使用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);


以上是JavaScript从数组构建数组的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>