需要得到JSON对象内的值的计数-java脚本


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

我的输出应该是

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

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

您可以使用Map, Set和reduce轻松实现结果

const 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",
},
];
const dict = jsondata.reduce((map, curr) => {
const objInMap = map.get(curr.unit);
if (!objInMap) {
map.set(curr.unit, {
unitname: curr.unit,
no_of_accounts: 1,
accounts_name: new Set([curr.account]),
});
} else {
++objInMap.no_of_accounts;
objInMap.accounts_name.add(curr.account);
}
return map;
}, new Map());
const result = [];
for (let obj of dict.values()) {
const o = { ...obj, accounts_name: [...obj.accounts_name] };
result.push(o);
}
console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

这里我有forEachmap方法来获得结果,您可以在谷歌上搜索Array的这些功能。

let 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"}
];
let result = mapData(data);
console.log(result);

// main function to get your expected result
function mapData(data) {
let output = [];
data.forEach(item => {
if(output.find(a => a.unitname == item.unit)) return;
let unitname = item.unit;
let accounts = data.filter(a => a.unit == item.unit);
let no_of_accounts = accounts.length;
let accounts_name = accounts.map(a => a.account);
accounts_name = Array.from(new Set(accounts_name)); // remove duplicate accounts name
output.push({unitname, no_of_accounts, accounts_name});
});
return output;
}

相关内容

  • 没有找到相关文章

最新更新