使用lodash进行多级分组

时间:2019-04-12 11:42:04

标签: javascript arrays group-by lodash

我有下面的对象数组

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和{{1} }。

然后

2)我想与deviceIdkeyclassName分组并找到计数。

我该怎么做?

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

1 个答案:

答案 0 :(得分:3)

您可以将groupBymap方法链接在一起,以首先按键,地址和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>