【发布时间】:2021-06-27 08:04:50
【问题描述】:
我有一个这样的数组:
const arr = [ {name: 'Server 1', country: 'DE'}, {name: 'Server 2', country: 'PL'},
{name: 'Server 3', country: 'US'}, {name: 'Server 4', country: 'DE'},
{name: 'Server 5', country: 'US'}];
我想要的是group and count 得到如下输出:
[
{
"country": "DE",
"count": 2
},
{
"country": "PL",
"count": 1
},
{
"country": "US",
"count": 2
}
]
目前,我正在使用lodash,但我认为有更好的方法(例如,使用_groupBy 或类似的东西) 来解决它,对吧?
我的代码在这里:
const arr = [ {name: 'Server 1', country: 'DE'}, {name: 'Server 2', country: 'PL'}, {name: 'Server 3', country: 'US'}, {name: 'Server 4', country: 'DE'}, {name: 'Server 5', country: 'US'}];
const objectGroupby = _.countBy(arr, 'country');
const result = Object.entries(objectGroupby).map(([key, value]) => ({country: key, count: value}));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
如您所见,_.countBy(arr, 'country') 只是返回一个对象而不是数组。
{
"DE": 2,
"PL": 1,
"US": 2
}
那我得用Object.entries()&map来解决。
【问题讨论】:
标签: javascript group-by count lodash