gpt4 book ai didi

javascript - 使用 lodash 进行多级分组

转载 作者:行者123 更新时间:2023-11-30 11:05:49 26 4
gpt4 key购买 nike

我有下面的对象数组

const array = [
{
key: '11111',
address: { city: 'NY', country: 'USA' },
className: 'google.com',
deviceId: 'aaaaa'
},
{
key: '11111',
address: { city: 'NY', country: 'USA' },
className: 'google.com',
deviceId: 'aaaaa'
},
{
key: '33333',
address: { city: 'NY', country: 'USA' },
className: 'facebook.com',
deviceId: 'aaaaa'
},
{
key: '11111',
address: { city: 'NY', country: 'USA' },
className: 'google.com',
deviceId: 'ddddd'
},
{
key: '22222',
address: { city: 'Landon', country: 'UK' },
className: 'stackoverflow.com',
deviceId: 'ccccc'
},
{
key: '22222',
address: { city: 'Landon', country: 'UK' },
className: 'stackoverflow.com',
deviceId: 'ggggg'
},
{
key: '22222',
address: { city: 'Landon', country: 'UK' },
className: 'stackoverflow.com',
deviceId: 'fffff'
}
]

我需要下面的输出

[
{
"keys": {
"address": { "city": "NY", "country": "USA" },
"className": "google.com",
"key": "11111"
},
"count": 2
},
{
"keys": {
"address": { "city": "NY", "country": "USA" },
"className": "facebook.com",
"key": "33333"
},
"count": 1
},
{
"keys": {
"address": { "city": "Landon", "country": "UK" },
"className": "stackoverflow.com",
"key": "22222"
},
"count": 3
}
]

那么这里到底发生了什么。

1) 如果用户使用相同的 keyaddressclassName,我必须将用户视为唯一一个deviceId

然后

2) 我想用 keyclassNameaddress 分组并找到计数。

我该怎么做?

谢谢!!!请询问是否需要更多信息。

最佳答案

您可以将 groupBymap 方法链接到第一个按键、地址和类名分组,然后再执行一个 groupBy 来分组和计算具有唯一 deviceId

的元素

const array = [{"key":"11111","address":{"city":"NY","country":"USA"},"className":"google.com","deviceId":"aaaaa"},{"key":"11111","address":{"city":"NY","country":"USA"},"className":"google.com","deviceId":"aaaaa"},{"key":"33333","address":{"city":"NY","country":"USA"},"className":"facebook.com","deviceId":"aaaaa"},{"key":"11111","address":{"city":"NY","country":"USA"},"className":"google.com","deviceId":"ddddd"},{"key":"22222","address":{"city":"Landon","country":"UK"},"className":"stackoverflow.com","deviceId":"ccccc"},{"key":"22222","address":{"city":"Landon","country":"UK"},"className":"stackoverflow.com","deviceId":"ggggg"},{"key":"22222","address":{"city":"Landon","country":"UK"},"className":"stackoverflow.com","deviceId":"fffff"}]

const result = _.chain(array)
.groupBy(({ key, address: { city, country }, className }) => {
return `${key}-${city}-${country}-${className}`
}).map(e => {
const [{ key, address, className }] = e;
return {
keys: { key, address, className },
count: _.keys(_.groupBy(e, 'deviceId')).length
}
})

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

关于javascript - 使用 lodash 进行多级分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55650856/

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