如何在 JavaScript 中动态填充多维数组?
Posted
技术标签:
【中文标题】如何在 JavaScript 中动态填充多维数组?【英文标题】:How to dynamically populate a multidimensional array in JavaScript? 【发布时间】:2020-09-27 23:14:57 【问题描述】:我有一个从 URL 请求中获得的对象:
var data =
"DataSet":
"Series": [
"@FREQ": "A",
"@REF_AREA": "BF",
"@INDICATOR": "NGDP_R_PC_PP_PT",
"@UNIT_MULT": "0",
"@TIME_FORMAT": "P1Y",
"Obs": [
"@TIME_PERIOD": "2018",
"@OBS_VALUE": "6"
,
"@TIME_PERIOD": "2019",
"@OBS_VALUE": "5"
,
"@TIME_PERIOD": "2020",
"@OBS_VALUE": "1"
,
"@TIME_PERIOD": "2021",
"@OBS_VALUE": "5"
]
,
"@FREQ": "A",
"@REF_AREA": "CI",
"@INDICATOR": "NGDP_R_PC_PP_PT",
"@UNIT_MULT": "0",
"@TIME_FORMAT": "P1Y",
"Obs": [
"@TIME_PERIOD": "2018",
"@OBS_VALUE": "6"
,
"@TIME_PERIOD": "2019",
"@OBS_VALUE": "6"
,
"@TIME_PERIOD": "2020",
"@OBS_VALUE": "2"
,
"@TIME_PERIOD": "2021",
"@OBS_VALUE": "8"
]
]
我想要一个看起来像这样的数组,每个“Obs”数组中的每个年份和值都在它自己的数组中:
var dataSet = [
[["2018","6"],["2019","5"],["2020","1"],["2021","5"]],
[["2018","6"],["2019","6"],["2020","2"],["2021","8"]]
]
我试过这个:
let dataO = []
var dataSet = data.Series.map((x,index) =>
dataO.push(x.Obs.map(i=>i['@TIME_PERIOD']))
dataO.push(x.Obs.map(r=>r['@OBS_VALUE']))
return dataO
)
但我得到了一个包含 2 个元素的数组,每个元素都包含来自对象的所有数据。我看不出哪里出错了。任何帮助表示赞赏。谢谢!
【问题讨论】:
【参考方案1】:简单的双循环:
var dataSet = [];
data.DataSet.Series.map((x) =>
var periods = [];
x.Obs.map((y) =>
periods.push([y['@TIME_PERIOD'], y['@OBS_VALUE']]);
);
dataSet.push(periods);
);
可在下面测试:
var data =
"DataSet":
"Series": [
"@FREQ": "A",
"@REF_AREA": "BF",
"@INDICATOR": "NGDP_R_PC_PP_PT",
"@UNIT_MULT": "0",
"@TIME_FORMAT": "P1Y",
"Obs": [
"@TIME_PERIOD": "2018",
"@OBS_VALUE": "6"
,
"@TIME_PERIOD": "2019",
"@OBS_VALUE": "5"
,
"@TIME_PERIOD": "2020",
"@OBS_VALUE": "1"
,
"@TIME_PERIOD": "2021",
"@OBS_VALUE": "5"
]
,
"@FREQ": "A",
"@REF_AREA": "CI",
"@INDICATOR": "NGDP_R_PC_PP_PT",
"@UNIT_MULT": "0",
"@TIME_FORMAT": "P1Y",
"Obs": [
"@TIME_PERIOD": "2018",
"@OBS_VALUE": "6"
,
"@TIME_PERIOD": "2019",
"@OBS_VALUE": "6"
,
"@TIME_PERIOD": "2020",
"@OBS_VALUE": "2"
,
"@TIME_PERIOD": "2021",
"@OBS_VALUE": "8"
]
]
;
var dataSet = [];
data.DataSet.Series.map((x) =>
var periods = [];
x.Obs.map((y) =>
periods.push([y['@TIME_PERIOD'], y['@OBS_VALUE']]);
);
dataSet.push(periods);
);
console.log(dataSet);
【讨论】:
【参考方案2】:你可以使用flatMap
:
data.DataSet.Series
.flatMap(x => x.Obs)
.map(x => [x["@TIME_PERIOD"], x["@OBS_VALUE"]])
【讨论】:
谢谢,但这提供了一个包含所有值的数组。虽然很高兴了解 flatMap(),但我可以充分利用它。以上是关于如何在 JavaScript 中动态填充多维数组?的主要内容,如果未能解决你的问题,请参考以下文章