我如何从js中的分组对象数组返回值的数组?



我有一个订阅组数组,按类型(基本,中等…)'

[
[
"Basic",
[
{ "id": 2, "name": "Basic", "started_at": "2022-01-24", "count": 4 },
{ "id": 2, "name": "Basic", "started_at": "2022-03-16", "count": 2 },
{ "id": 2, "name": "Basic", "started_at": "2022-05-16", "count": 1 }
]
],
[
"Medium",
[
{ "id": 3, "name": "Medium", "started_at": "2022-02-21", "count": 1 },
{ "id": 3, "name": "Medium", "started_at": "2022-05-28", "count": 1 }
]
],
[
"Premium",
[{ "id": 4, "name": "Premium", "started_at": "2022-04-21", "count": 1 }]
],
[
"Master",
[
{ "id": 7, "name": "Master", "started_at": "2022-07-28", "count": 1 },
{ "id": 7, "name": "Master", "started_at": "2022-08-02", "count": 1 }
]
],
[
"Jedi",
[{ "id": 6, "name": "Jedi", "started_at": "2022-09-28", "count": 1 }]
]
]

我想做的是返回一个包含对象foreach sub的数组,其中包含以下数据(按月获取计数值):'

[
{
label: "Basic",
data: [4, 0, 2, 0, 1,0],
},
{
label: "Medium",
data: [0, 1, 0, 0, 1,0],
},
...
]

数据字段应该包含每个订阅对应月份的count字段。例如,计数4在1月,计数2在3月,它将返回[4,0,1],2月为0。

我该怎么做呢?

我这样做了,但它只返回现有的月份值,所以没有办法知道该值是哪个月份。

subscriptions.map((item) => {
return {
label: item[0],
data: item[1].map((value, index) => {
return value.count;
}),
};
})

您可以将数组reduce并创建一个映射器对象,该对象将每个计划映射为特定月份的count。像这样:

{
"Basic": {
"1": 4,
"3": 2,
"5": 1
},
"Medium": {
"2": 1,
"5": 1
},
...
}

然后循环遍历对象的条目并创建计划为label的对象和length: 12数组,并使用索引

获取特定月份的数据

const input=[["Basic",[{id:2,name:"Basic",started_at:"2022-01-24",count:4},{id:2,name:"Basic",started_at:"2022-03-16",count:2},{id:2,name:"Basic",started_at:"2022-05-16",count:1}]],["Medium",[{id:3,name:"Medium",started_at:"2022-02-21",count:1},{id:3,name:"Medium",started_at:"2022-05-28",count:1}]],["Premium",[{id:4,name:"Premium",started_at:"2022-04-21",count:1}]],["Master",[{id:7,name:"Master",started_at:"2022-07-28",count:1},{id:7,name:"Master",started_at:"2022-08-02",count:1}]],["Jedi",[{id:6,name:"Jedi",started_at:"2022-09-28",count:1}]]];
const mapper = input.reduce((acc, [plan, subscriptions]) => {
acc[plan] ??= {}
for(const { started_at, count } of subscriptions)
acc[plan][+started_at.slice(5,7)] = count

return acc;
}, {})
const output = 
Object.entries(mapper)
.map( ([label, subData]) => ({ 
label, 
data: Array.from({ length: 12 }, (_, i) => subData[i+1] ?? 0) 
}) )

console.log(output)

注意:

  • 假设数据仅为一年。如果可以跨越数年,则必须创建另一个嵌套级别:

    {
    "Basic": {
    "2022": {
    "1": 3
    }
    }
    }
    
  • 使用
  • started_at.slice(5,7)获取月号。如果日期不是ISO 8601格式,您可以使用new Date(started_at).getMonth() + 1来获取月份部分。

最新更新