gpt4 book ai didi

javascript - 获取对象数组中出现次数的计数

转载 作者:行者123 更新时间:2023-11-30 20:42:55 24 4
gpt4 key购买 nike

var json = [{
"city": "California",
"name": "Joe",
"age": 17
}, {
"city": "California",
"name": "Bob",
"age": 17
}, {
"city": "California",
"name": "Bob",
"age": 35
}, {
"city": "Texas",
"name": "Bob",
"age": 35
}, {
"city": "Florida",
"name": "Bob",
"age": 35
}
];

我只是为了不发生基于城市值(value)的事件,即输出如下。

updatedjson=[{"name":"California","count":3},{"name":"Texas","count":1},{"name":"Florida","count":1}]

使用任何使用 lodash 或 javascript 的方法

最佳答案

使用 Lodash,这将是:

const updatedJson = _(json)
.countBy('city')
.map((count, name) => ({ name, count }))
.value();

const json = [{"city":"California","name":"Joe","age":17},{"city":"California","name":"Bob","age":17},{"city":"California","name":"Bob","age":35},{"city":"Texas","name":"Bob","age":35},{"city":"Florida","name":"Bob","age":35}];

const updatedJson = _(json)
.countBy('city')
.map((count, name) => ({ name, count }))
.value();

console.log(JSON.stringify(updatedJson));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

关于javascript - 获取对象数组中出现次数的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49050863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com