Skip to content
Advertisement

need to get the count of values inside the a JSON object -java script

jsondata= 
   [{"unit": "H1", "account": "ambro","domain": "DFRE"},
    {"unit": "H1","account": "ambro","domain": "DFRE"},
    {"unit": "H2","account": "Honda","domain": "HRO"},
    {"unit": "H2","account": "ford","domain": "HRO"}  ]

my output should be

{unitname : H1,no_of_accounts : 2,accounts_name:[ambro]},
{unitname : H2,no_of_accounts : 2,accounts_name:[ford,Honda]}

Advertisement

Answer

const data = [
    {"unit": "H1", "account": "ambro","domain": "DFRE"},
    {"unit": "H1","account": "ambro","domain": "DFRE"},
    {"unit": "H2","account": "Honda","domain": "HRO"},
    {"unit": "H2","account": "ford","domain": "HRO"} 
];

const res = data.reduce((a, {unit, account}) => {
    a[unit] = a[unit] ?
        { ...a[unit], no_of_accounts: a[unit].no_of_accounts+1, accounts_name: [...new Set([...a[unit].accounts_name, account])] }
        :
        { unitname: unit, no_of_accounts:1, accounts_name: [account] };

    return a;
}, {});

console.log(Object.values(res));
.as-console-wrapper { max-height: 100% !important; top: 0; }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement