我有一个从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个元素的数组,每个元素包含来自对象的所有数据。我看不到我要去哪里错了。任何帮助表示赞赏。谢谢!
您可以使用flatMap
:
flatMap
简单的双循环:
data.DataSet.Series
.flatMap(x => x.Obs)
.map(x => [x["@TIME_PERIOD"], x["@OBS_VALUE"]])
下面可测试:
var dataSet = [];
data.DataSet.Series.map((x) => {
var periods = [];
x.Obs.map((y) => {
periods.push([y['@TIME_PERIOD'], y['@OBS_VALUE']]);
});
dataSet.push(periods);
});