【发布时间】:2021-08-17 05:14:50
【问题描述】:
我有一个具有以下结构的对象数组:
[
{
_id: 60b18e0a7ba49519c1ee63b4,
course: 'sfsdf',
earnings: 100,
creator: '607497d5f4bcc83fa1f3cedf',
month: 1,
year: 2019
},
{
_id: 60b18e1a7ba49519c1ee63b5,
course: 'sfsdf',
earnings: 200,
creator: '607497d5f4bcc83fa1f3cedf',
month: 2,
year: 2019
},
{
_id: 60b18e227ba49519c1ee63b6,
course: 'sfsdf',
earnings: 300,
creator: '607497d5f4bcc83fa1f3cedf',
month: 3,
year: 2019
},
{
_id: 60b18e297ba49519c1ee63b7,
course: 'sfsdf',
earnings: 400,
creator: '607497d5f4bcc83fa1f3cedf',
month: 4,
year: 2019
},
{
_id: 60b18b907ba49519c1ee63a5,
course: 'html-css',
earnings: 1000,
creator: '607497d5f4bcc83fa1f3cedf',
month: 3,
year: 2021
},
{
_id: 60b18c457ba49519c1ee63a9,
course: 'html-css',
earnings: 500,
creator: '607497d5f4bcc83fa1f3cedf',
month: 2,
year: 2020
}
]
我想以某种方式操作上面的数组,使结果看起来像:
[
{ label: 2019, earnings: 1000 },
{ label: 2021, earnings: 1000 },
{ label: 2020, earnings: 500 },
]
其中label 是唯一的年份,earnings 是该年份所有收入的总和。
问题说明:
-
2019 年有 4 个对象,每年的收益分别为 100、200、300、400,总计为 1000(100 + 200 + 300 + 400),因此结果数组有
{ label: 2019, earnings: 1000 } -
2021 年有 1 个对象,收入为 1000,因此总收入为 1000,因此结果数组有
{ label: 2021, earnings: 1000 }
2020 年也是如此。
【问题讨论】:
标签: javascript arrays mapreduce javascript-objects reduce