对数组的对象进行分组和计数并创建新的数组 [英] group and count objects of array and create new array

查看:76
本文介绍了对数组的对象进行分组和计数并创建新的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用reactJS并从响应中获得一个动态对象数组,如下所示:

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" } ]

动态数组最多可以包含许多不同的类型,但我的仪表板只能使用3种颜色(好,警告,严重).如果多次使用颜色,这不是问题!

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.

(注意:我不想使用LINQ.js之类的额外JavaScript库)

(Note: I would not like to use extra javascript libraries like LINQ.js )

您能帮我吗?

推荐答案

您可以使用reduce将数组分组为一个对象.使用Object.values将对象转换为数组.

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);

随机选择颜色:

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);

这篇关于对数组的对象进行分组和计数并创建新的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆