原本数据格式:
let list2 = [
{
name: "教学机构",
value: [
{
name: "专业资源库",
value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 0}, {name: "2021-2022", value: 0}]
},
{
name: "专业教学资源库",
value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 0}, {name: "2021-2022", value: 0}]
}
]
},
{
name: "教学机构2",
value: [
{
name: "专业资源库",
value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 0}, {name: "2021-2022", value: 0}]
},
{
name: "专业教学资源库",
value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 0}, {name: "2021-2022", value: 0}]
}
]
},
{
name: "教学机构3",
value: [
{
name: "专业资源库",
value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 0}, {name: "2021-2022", value: 0}]
},
{
name: "专业教学资源库",
value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 0}, {name: "2021-2022", value: 0}]
}
]
}
]
目标格式转换如下:
实现目标格式一:
let targetArr1 = [ { name: "专业资源库", value: [ { name: "教学机构1", value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 0}, {name: "2021-2022", value: 0}] }, { name: "教学机构2", value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 1}, {name: "2021-2022", value: 0}] }, { name: "教学机构3", value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 2}, {name: "2021-2022", value: 3}] } ] }, { name: "专业教学资源库", value: [ { name: "教学机构1", value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 0}, {name: "2021-2022", value: 0}] }, { name: "教学机构2", value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 1}, {name: "2021-2022", value: 0}] }, { name: "教学机构3", value: [{name: "2019-2020", value: 0}, {name: "2020-2021", value: 1}, {name: "2021-2022", value: 10}] } ] }, ]
实现目标格式二:
统计属性值name为年份的value总和let targetArr2 = [ { name: "专业资源库", value: [ {name: "2019-2020", value: 0}, {name: "2020-2021", value: 1}, {name: "2021-2022", value: 5} ] }, { name: "专业教学资源库", value: [ {name: "2019-2020", value: 0}, {name: "2020-2021", value: 2}, {name: "2021-2022", value: 10} ] }, ]
分组和 Sum 懒得自己写,用的 Lodash,所以就用 Lodash 来处理了。
写了篇博文:在前端使用 JS 进行分类汇总