首页 > 解决方案 > 用lodash按两个变量对对象数组进行分组

问题描述

我有以下数据结构:

[
{ date: 12.12.20,
  country: Italy,
  categoryType: one
},
{ date: 12.12.20,
  country: Germany,
  categoryType: one
},
{ date: 15.12.20,
  country: France,
  categoryType: two
}
]

我正在尝试按两个变量进行分组:(1)日期,然后在每个日期(2)按国家/地区分组类型。

我成功按日期分组,但我不知道如何按国家分组。

我想要以下内容,最好使用 lodash.js:

        [
        { date: 12.12.20,
          country: [
         Italy: [categoryType: one],
         Germany: [categoryType: one]]
}, 
    {...}]

这是我的代码

_.chain(data)
          .groupBy('date')
          .map((dates, date)=> {
            const country = _.map(dates, 'country');
           
            return {
               date: date,
               country: country,
          }
        }).value()

标签: javascriptarrayslodash

解决方案


您可以执行以下操作。

const data = [
  {
    date: "12.12.20",
    country: "Italy",
    categoryType: "one"
  },
  {
    date: "12.12.20",
    country: "Germany",
    categoryType: "one"
  },
  {
    date: "15.12.20",
    country: "France",
    categoryType: "two"
  }
]

console.log(
  _.mapValues(
    _.groupBy(data, 'date'),
    e => _.groupBy(e, 'country')
  )
)

这应该会产生所需的输出:

{
  '12.12.20': {
    'Italy': [
      {
        'date': '12.12.20',
        'country': 'Italy',
        'categoryType': 'one'
      }
    ],
    'Germany': [
      {
        'date': '12.12.20',
        'country': 'Germany',
        'categoryType': 'one'
      }
    ]
  },
  '15.12.20': {
    'France': [
      {
        'date': '15.12.20',
        'country': 'France',
        'categoryType': 'two'
      }
    ]
  }
}

推荐阅读