JavaScript按两个属性对JSON对象进行分组并计数
我有一个如下所示的JSON对象:
long_array =
[
{"location":"Kirrawee","identity_long":"student"},
{"location":"Kirrawee","identity_long":"visitor"},
{"location":"Kirrawee","identity_long":"visitor"},
{"location":"Kirrawee","identity_long":"worker"},
{"location":"Sutherland","identity_long":"student"},
{"location":"Sutherland","identity_long":"resident"},
{"location":"Sutherland","identity_long":"worker"},
{"location":"Sutherland","identity_long":"resident"},
{"location":"Miranda","identity_long":"resident"},
{"location":"Miranda","identity_long":"worker"},
{"location":"Miranda","identity_long":"student"},
{"location":"Miranda","identity_long":""},
{"location":"Miranda","identity_long":"worker"},
{"location":"Miranda","identity_long":"resident"}
];
我要实现的对象如下:
grouped_and_counted_location_and_identity =
[
{"location":"Kirrawee","identity":"student","count":1},
{"location":"Kirrawee","identity":"visitor","count":2},
{"location":"Kirrawee","identity":"worker","count":1},
{"location":"Sutherland","identity":"student","count":1},
{"location":"Sutherland","identity":"resident","count":2},
{"location":"Sutherland","identity":"worker","count":1},
{"location":"Miranda","identity":"resident","count":2},
{"location":"Miranda","identity":"worker","count":2},
{"location":"Miranda","identity":"student","count":1}
];
我发现这在R语言中非常容易实现,我会这样做:
long_array %>%
group_by(location, identity_long) %>%
summarise(n = n())
甚至只是
long_array %>%
count(location, identity_long)
但是我如何在Java脚本中实现这一点?
我只想按两个属性对JSON对象进行分组,并计算相同出现的次数。
解决方案
您可以使用库(如loDash)并使用其GROUP BY函数来实现此简单方法,但实现您自己的GROUP BY函数会比较耗时。
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">let long_array = [{
"location": "Kirrawee",
"identity_long": "student"
},
{
"location": "Kirrawee",
"identity_long": "visitor"
},
{
"location": "Kirrawee",
"identity_long": "visitor"
},
{
"location": "Kirrawee",
"identity_long": "worker"
},
{
"location": "Sutherland",
"identity_long": "student"
},
{
"location": "Sutherland",
"identity_long": "resident"
},
{
"location": "Sutherland",
"identity_long": "worker"
},
{
"location": "Sutherland",
"identity_long": "resident"
},
{
"location": "Miranda",
"identity_long": "resident"
},
{
"location": "Miranda",
"identity_long": "worker"
},
{
"location": "Miranda",
"identity_long": "student"
},
{
"location": "Miranda",
"identity_long": ""
},
{
"location": "Miranda",
"identity_long": "worker"
},
{
"location": "Miranda",
"identity_long": "resident"
}
];
function addItemCounts(items, groupByKeys) {
var groups = _.groupBy(long_array, obj => {
return groupByKeys.map(key => obj[key]).join('-');
});
return _.map(groups, g => ({
...g[0],
count: g.length
}));
}
console.log(addItemCounts(long_array, ['identity_long', 'location']));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
相关文章