javascript - 用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()
解决方案
您可以执行以下操作。
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'
}
]
}
}
推荐阅读
- c# - 如何收集“ᑕƘᏔ®✞ℍ”等特殊字母
- assembly - 如何将来自控制台的整数输入存储到变量中
- functional-programming - 在 OCaml 中的对列表中查找重复项
- firebase - firebase 中的出站网络到底是什么
- typescript - 类型中缺少属性,但它是必需的
- javascript - 在 IE 上禁用 CTRL+Shift_Enter
- javascript - 如何使用javascript为页面中的所有元素添加事件监听器,它们的ID在我的数组中
- python - 在具有一行零的矩阵中,如何用一个替换矩阵的相应对角线条目?
- flutter - 每次在 Flutter 中加载页面时显示新的共享首选项值?
- python - 如何将python变量传递给shell scriptT