我有下面的对象数组
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)如果用户具有相同的key
,address
,className
和{{1} }。
然后
2)我想与deviceId
,key
和className
分组并找到计数。
我该怎么做?
谢谢!!!请询问是否需要更多信息。
答案 0 :(得分:3)
您可以将groupBy
和map
方法链接在一起,以首先按键,地址和className分组,然后再进行一次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>