首页 > 解决方案 > JavaScript 从数组构建数组

问题描述

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

我当前的数组结构:

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

我正在寻找构建两个数组,即一个用于汇总值,一个用于类值。

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

标签: javascript

解决方案


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


推荐阅读