GROUP BY in JavaScript-平面数组到嵌套的JSON
我的前端打字文件中有以下列表:
月:
0: {id: 1, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-12-15T00:00:00", purchaseMonthString: "Dec-2019" , year: 2019, month: "December"}
1: {id: 2, companyName: "company5", companyId: 5, flActive: true, purchaseMonth: "2019-12-15T00:00:00", …}
2: {id: 3, companyName: "company13", companyId: 13, flActive: true, purchaseMonth: "2019-11-15T00:00:00", …}
3: {id: 4, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-11-15T00:00:00", …}
4: {id: 5, companyName: "company5", companyId: 5, flActive: true, purchaseMonth: "2019-10-15T00:00:00", …}
5: {id: 6, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2020-09-15T00:00:00", …}
6: {id: 7, companyName: "company7", companyId: 7, flActive: true, purchaseMonth: "2020-09-15T00:00:00", …}
我希望从中得到一个嵌套的树JSON,按CompnayName和Year属性分组,类似于下面的内容,但采用JSON格式:
我发现了这段代码,但它没有完全返回结果,需要稍微调整一下:
keys = [
'year',
'companyName'
];
groupBy() {
const drill = (o, key, ...keys) =>
key ? drill((o[key] = o[key] || {}), ...keys) : o;
const result = {};
for (const e of this.poMonths) {
const key = drill(
result,
e.companyName,
e.year,
e.month
);
}
return result;
}
如何才能使其正常工作?
解决方案
您可以使用array.reduce()构建树。它从一个空对象开始,当在特定键下还没有定义对象/数组时(将执行||
运算符的右侧):
let input = [{id: 1, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-12-15T00:00:00", year: 2019, month: "December"},
{id: 2, companyName: "company5", companyId: 5, flActive: true, purchaseMonth: "2019-12-15T00:00:00", year: 2019, month: "December"},
{id: 3, companyName: "company13", companyId: 13, flActive: true, purchaseMonth: "2019-11-15T00:00:00", year: 2019, month: "November"},
{id: 4, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-11-15T00:00:00", year: 2019, month: "December"},
{id: 5, companyName: "company5", companyId: 5, flActive: true, purchaseMonth: "2019-10-15T00:00:00", year: 2019, month: "October"},
{id: 6, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2020-09-15T00:00:00", year: 2020, month: "September"},
{id: 7, companyName: "company7", companyId: 7, flActive: true, purchaseMonth: "2020-09-15T00:00:00", year: 2020, month: "September"}]
let months = { "09": "September", "10": "October", "11": "November", "12": "December" }
let result = input.reduce((state,current) => {
let {companyName, year, month} = current;
let company = state[companyName] || (state[companyName] = {});
let yearObj = company[year] || (company[year] = {});
let monthArr = yearObj[month] || (yearObj[month] = []);
monthArr.push(current);
return state;
}, {});
console.log(result);
相关文章