【发布时间】:2020-04-20 04:35:36
【问题描述】:
目前我正在使用一个 api,它返回一个看起来像的对象数组
[{match_id: "255232",
country_id: "41",
country_name: "England",
league_id: "152",
league_name: "National League",
match_date: "2020-01-01",
match_status: "",
match_time: "16:00"},
{match_id: "255232",
country_id: "41",
country_name: "Italy",
league_id: "152",
league_name: "Serie a",
match_date: "2020-01-01",
match_status: "",
match_time: "16:00"},
{match_id: "255232",
country_id: "41",
country_name: "Italy",
league_id: "153",
league_name: "Serie b",
match_date: "2020-01-01",
match_status: "",
match_time: "16:00"},...
...
]
我想以一种最终看起来像这样的方式对其进行改造:
const transformed = [
{
country_name: "England",
entries: [
{league_name: "National League",
events: [{},{}]}
]
},
{country_name: "Italy",
entries: [
{
league_name: "Serie a",
events: [{},{}]
},
{
league_name: "Serie b",
events: [{},{}]
}...
]]
我尝试使用 .reduce,但没有得到预期的输出,我最终得到的只是一个还原的结构。基本上我需要的是首先按国家名称和联赛名称进行分类。
显然数据是动态的,国家/联赛的名称经常变化。
【问题讨论】:
-
我会尝试使用 map 来遍历列表并返回一个您想要的格式的新列表。
-
一些答案建议对结果数据使用键控对象。我认为这个建议很好,并建议您考虑数据的结果“形状”(每个@tex)对最终输出的重要性。
标签: javascript arrays node.js object