如何对数组进行分组并获得具有相似类型/组织的所有记录的计数 [英] How can I group an array and get count of all the records having similar type/org

查看:45
本文介绍了如何对数组进行分组并获得具有相似类型/组织的所有记录的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 array orglist ,其字段为 organization .在同一阵列中或新阵列中,我需要统计所有在场的组织.

I have an array orglist with field organization. In the same array or new I need count of all the org present.

这是我的数组

{
    "orgId": 56,
    "org": "EDC",
    "Id": 816,
},
{
    "orgId": 37,
    "org": "EDC",
    "Id": 85425,
},
{
    "orgId": 68,
    "org": "AXC",
    "Id": 85427,
},
{
    "orgId": 28,
    "org": "SEE",
    "Id": 858,
}

我正在寻找此输出

{
    "orgId": 56,
    "org": "EDC",
    "Id": 816,
    "orgCount":"2"
    
},
{
    "orgId": 37,
    "org": "EDC",
    "Id": 85425,
    "orgCount":"2"
},
{
    "orgId": 68,
    "org": "AXC",
    "Id": 85427,
    "orgCount":"1"
},
....

我尝试了以下解决方案,但只提供了 count org 值,并排除了所有其他字段

I tried below solution but that provide me only count and org value and excluding all other fields

var counts = this.orglist.reduce((p, c) => {
var name = c.org;
if (!p.hasOwnProperty(name)) {
p[name] = 0;
}
p[name]++;
return p;
}, {});

如何获得预期的输出?

推荐答案

一种方法是分两个阶段的过程,首先计算每个 org 值的出现,然后添加该属性输入对象:

One way to do this is a two-stage process, first to count the occurrences of each org value, and then to add that property to the input objects:

let orglist = [{
    "orgId": 56,
    "org": "EDC",
    "Id": 816,
},
{
    "orgId": 37,
    "org": "EDC",
    "Id": 85425,
},
{
    "orgId": 68,
    "org": "AXC",
    "Id": 85427,
},
{
    "orgId": 28,
    "org": "SEE",
    "Id": 858,
}];

const counts = orglist.reduce((c, o) => {
   c[o.org] = c[o.org] || 0;
   c[o.org]++;
   return c;
}, {});

orglist = orglist.map(({org, ...rest}) => ({ ...rest, org, "orgCount" : counts[org] }));

console.log(orglist);

这篇关于如何对数组进行分组并获得具有相似类型/组织的所有记录的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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