作者:mobiledu2502885523 | 来源:互联网 | 2023-06-08 21:57
我目前有一个有 2 个级别的数组。我试图从初始数组构建两个新数组,但似乎坚持使用的方法。我尝试了 forEach()、while 循环以及 push 都无济于事。我当前的数组结构:[ { "a
我目前有一个有 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);