我的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来做到这一点呢?
我最终要做的是在表中显示一些旋转的数据。我不知道什么是最好的设计才能做到这一点。
现在,我只是动态地设置一个表,并添加对应于每一行的数据。这样做有更好的设计模式吗?
发布于 2016-11-18 03:48:20
可以使用类别作为键将对象数组缩减为对象,并添加月份,然后再将其映射回数组。
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);
发布于 2016-11-18 03:37:49
我将采取以下办法:
例如,您的算法可能如下所示:
有时候大声朗读算法会有帮助。或者在黑板上将算法动画化。或者和附近的人通过算法交谈。
伪代码可能是:
category属性设置为"Amazon",将months属性设置为空对象。months属性添加一个新属性,其键是来自该元素的month属性的值,其值是来自该元素的total属性的值。如果您对这些步骤中的任何一个有特定的问题,您可以进一步研究,或者询问,例如:
如果您不熟悉上面使用的任何术语--比如数组、对象、属性、键、值或元素--研究它们,并确保您知道它们的含义。了解和使用正确的术语是成功编程的第一步!
当将算法转换为JS时,一步一步地编写,并在每个阶段进行测试。例如,从一个根本不循环输入的版本开始,并确保它生成正确的[{category: "Amazon", month: {}}]输出。在下面的每一步,在调试器中遍历您的代码--如果您不知道如何使用调试器,那么学习这应该是您的首要任务!如果您想检查一下语法,为了确保它能执行您的想法,只需在控制台中键入它就可以了。如果您不知道控制台是什么,那么学习应该是另一个首要任务。
以上所有的假设都假设您有一个Amazon类别。如果要有多个类别,并且希望输出数组中有多个对象(每个对象一个),那么从顶部开始,编写算法和伪代码来处理这个问题。
https://stackoverflow.com/questions/40668896
复制相似问题