问题
I am using reactJS and have an dynamic array of object from an response which looks like the following:
[{ 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" } ]
The dynamic array can have to up to many different types but I have only 3 colors to use in my dashboard (ok, warning, critical). Its not a problem if the color is used multiple times!
I would like to create a new array for my dashboard to group and count my response and merge it with the colors to get the following result:
[{ name: "new", value: 2, color: 'ok' }, { name: "old", value: 1, color: 'warning' }, { name: "broken", value: 1, color: 'critical' }, { name: "used", value: 2, color: 'ok' }]
So, first of all I need to group them, count the objects in the groups, select an color and then create a new array.
(Note: I would not like to use extra javascript libraries like LINQ.js )
Could yo help me please?
回答1:
You can use reduce
to group the arrays into an object. Use Object.values
to convert the object into an array.
You can define the colors on an object using the type as the key.
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);
Choosing the colors randomly:
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);
来源:https://stackoverflow.com/questions/50913026/group-and-count-objects-of-array-and-create-new-array