我正在使用reactJS并从响应中获得一个动态的对象数组,如下所示:
[{ year: 2016, origin: "EN", type: "new" }, { year: 2016, origin: "EN", type: "old" }, { year: 2016, origin: "EN", type: "used" }, { year: 2016, origin: "EN", type: "new" }, { year: 2016, origin: "EN", type: "broken" }, { year: 2016, origin: "EN", type: "used" } ]
动态数组可以有多达不同的类型,但我的仪表板中只能使用3种颜色(ok,warning,critical)。如果颜色多次使用,这不是问题!
我想为我的仪表板创建一个新数组,以便对我的响应进行分组和计数,并将其与颜色合并以获得以下结果:
[{ name: "new", value: 2, color: 'ok' }, { name: "old", value: 1, color: 'warning' }, { name: "broken", value: 1, color: 'critical' }, { name: "used", value: 2, color: 'ok' }]
所以,首先我需要对它们进行分组,计算组中的对象,选择颜色然后创建一个新数组。
(注意:我不想使用像LINQ.js这样的额外javascript库)
你能帮我吗?
答案 0 :(得分:2)
您可以使用reduce
将数组分组到对象中。使用Object.values
将对象转换为数组。
您可以使用类型作为键来定义对象上的颜色。
let arr = [{ year: 2016, origin: "EN", type: "new" }, { year: 2016, origin: "EN", type: "old" }, { year: 2016, origin: "EN", type: "used" }, { year: 2016, origin: "EN", type: "new" }, { year: 2016, origin: "EN", type: "broken" }, { year: 2016, origin: "EN", type: "used" } ]
let colors = {'new' : 'ok', 'old' : 'warning', 'broken' : 'critical', 'used' : 'ok'}
let result = Object.values(arr.reduce((c, {type}) => {
c[type] = c[type] || {name: type,value: 0,color: colors[type]};
c[type].value++;
return c;
}, {}))
console.log(result);
随机选择颜色:
let arr = [{ year: 2016, origin: "EN", type: "new" }, { year: 2016, origin: "EN", type: "old" }, { year: 2016, origin: "EN", type: "used" }, { year: 2016, origin: "EN", type: "new" }, { year: 2016, origin: "EN", type: "broken" }, { year: 2016, origin: "EN", type: "used" } ]
let colors = ['ok', 'warning', 'critical'];
let result = Object.values(arr.reduce((c, {type}) => {
c[type] = c[type] || {name: type,value: 0,color: colors[Math.floor(Math.random() * colors.length)]};
c[type].value++;
return c;
}, {}))
console.log(result);