gpt4 book ai didi

javascript - 像数据透视表一样在 javascript 中格式化 json 数据

转载 作者:行者123 更新时间:2023-11-30 08:29:05 25 4
gpt4 key购买 nike

我的 api 返回了以下数据。

[{"category":"Amazon","month":"Feb","total":9.75},
{"category":"Amazon","month":"Mar","total":169.44},
{"category":"Amazon","month":"Apr","total":10.69},
{"category":"Amazon","month":"May","total":867.0600000000001},
{"category":"Amazon","month":"Jun","total":394.43999999999994},
{"category":"Amazon","month":"Jul","total":787.2400000000001},
{"category":"Amazon","month":"Aug","total":1112.4400000000003},
{"category":"Amazon","month":"Sep","total":232.86999999999998},
{"category":"Amazon","month":"Oct","total":222.26999999999998},
{"category":"Amazon","month":"Nov","total":306.09999999999997},
{"category":"Amazon","month":"Dec","total":1096.2599999999998}]

我想格式化它,使月份都分组在每个类别下,如下所示:

[{"category":"Amazon","month":{"Jan":9.75,"Feb":9.75,"Mar":9.75,"Apr":9.75,etc...}]

我如何使用 javascript 执行此操作?

我最终要做的是在表格中显示一些旋转数据。我不确定实现此目标的最佳设计是什么。

现在,我只是动态地设置一个表并添加与每一行对应的数据。是否有更好的设计模式来执行此操作?

最佳答案

您可以使用类别作为键将对象数组缩减为一个对象,并添加月份,然后再次将其映射回数组

var arr = [{"category":"Amazon","month":"Feb","total":9.75},
{"category":"Amazon","month":"Mar","total":169.44},
{"category":"Amazon","month":"Apr","total":10.69},
{"category":"Amazon","month":"May","total":867.0600000000001},
{"category":"Amazon","month":"Jun","total":394.43999999999994},
{"category":"Amazon","month":"Jul","total":787.2400000000001},
{"category":"Amazon","month":"Aug","total":1112.4400000000003},
{"category":"Amazon","month":"Sep","total":232.86999999999998},
{"category":"Amazon","month":"Oct","total":222.26999999999998},
{"category":"Amazon","month":"Nov","total":306.09999999999997},
{"category":"Amazon","month":"Dec","total":1096.2599999999998}];

var o = arr.reduce( (a,b) => {
a[b.category] = a[b.category] || [];
a[b.category].push({[b.month]:b.total});
return a;
}, {});

var a = Object.keys(o).map(function(k) {
return {category : k, month : Object.assign.apply({},o[k])};
});

console.log(a);

关于javascript - 像数据透视表一样在 javascript 中格式化 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40668896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com