javascript - 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);
推荐阅读
- r - 如何从打印膏中编织输出
- c# - 添加 KeepFileOpen="true" 后 NLog 丢弃消息
- tensorflow - 在大文本上微调 GPT-2 以生成域文本
- c# - 当前任务调度程序是否流入 ThreadPool.QueueUserWorkItem 回调?
- r - 使用 dplyr 拆分-应用-组合以缩放分组变量中的向量
- sql - 在雪花中解析数据
- gnuplot - 将 gnuplot 的热图拟合到帧大小
- django - 如何将日志记录写入现有的错误日志文件
- blazor - 在 Blazor Server 中访问 AuthenticationState 以在一个地方更新组件
- unit-testing - 单元测试中的新核心数据堆栈(PersistenceController)