我的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执行此操作?
我最终要做的是在表格中显示一些透视数据。我不确定最好的设计是什么来实现这一点。
现在,我只是动态设置一个表并添加与每行对应的数据。这样做有更好的设计模式吗?
答案 0 :(得分:3)
我会采取以下方法:
例如,您的算法可能如下所示:
有时,向您自己大声朗读算法会有所帮助。或者在黑板上制作算法动画。或者与附近的人讨论算法。
伪代码可能是:
category
属性设置为"Amazon"
,months
属性设置为空对象。months
属性,其键是元素中month
属性的值,其属性为 value 是元素中total
属性的值。如果您对这些步骤有任何具体问题,可以进一步研究,或者询问,例如:
如果您不熟悉上面使用的任何术语 - 例如 array , object , property , key < / em>, value 或元素 - 研究它们并确保您知道它们的含义。了解和使用正确的术语是成功编程的第一步!
将算法转换为JS时,请逐步编写,并在每个阶段进行测试。例如,从一个根本没有在输入上循环的版本开始,并确保它产生[{category: "Amazon", month: {}}]
的正确输出。在此debugger以及后续步骤中使用Caused by: java.lang.OutOfMemoryError: Java heap space中的代码 - 如果您不知道如何使用调试器,请了解这应该是您的首要任务!如果你想检查一点语法,为了确保它符合你的想法,只需在控制台中输入即可试用。如果你不知道控制台是什么,那么学习它应该是另一个首要任务。
以上所有假设您都拥有一个亚马逊类别。如果你要在输出数组中有多个类别,并且想要多个对象(每个对应一个),那么从顶部开始,编写可以处理的算法和伪代码。
答案 1 :(得分:2)
您可以使用类别作为键将对象数组缩减为对象,然后添加月份,然后再将其映射回数组
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);