简体   繁体   English

使用Lodash通过多个属性对对象数组进行分组

[英]Group array of objects by multiple properties with Lodash

is possible with lodash library group elements by 2 properties? lodash库组元素有2个属性是可能的吗? I have array of objects like this: 我有这样的对象数组:

[{
   id: 1,
   amount: 2000,
   date: "2018-01-31T00:00:00.000Z"
},{
   id: 2,
   amount: 3000,
   date: "2017-07-31T00:00:00.000Z"
},{
   id: 3,
   amount: 6000,
   date: "2018-01-31T00:00:00.000Z"
},{
   id: 4,
   amount: 7000,
   date: "2017-01-31T00:00:00.000Z"
},{
   id: 5,
   amount: 5000,
   date: "2017-03-31T00:00:00.000Z"
},{
   id: 6,
   amount: 3000,
   date: "2018-02-22T00:00:00.000Z"
},{
   id: 7,
   amount: 4500,
   date: "2017-01-31T00:00:00.000Z"
}]

My goal is group objects in array by: 我的目标是通过以下方式将数组中的对象分组:

  1. year
  2. month

Purpose of that grouping is that I need in result order these objects' sum of amount by newest. 该分组的目的是我需要按最新顺序排序这些对象的数量之和。 So for that reason I need distinguish January 2017 from January 2018. It should be 2 different groups. 因此,出于这个原因,我需要将2017年1月与2018年1月区分开。应该是2个不同的组。

I am not sure if my approach is correct so I write here my required output: 我不确定我的方法是否正确,因此我在此处编写所需的输出:

[
  3000, // sum of 2018-2
  8000, // sum of 2018-1
  3000 // sum of 2017-7
  5000 // sum of 2017-3
  11500 // sum of 2017-1
]

I tried following command but it doesn't work and give me error: 我尝试了以下命令,但它不起作用,并给我错误:

  let xxx = _(data)
    .groupBy(function(i) {
      new Date(i.date).getFullYear()
    })
    .groupBy(function(i) {
      new Date(i.date).getMonth()
    })
    .map(x => x.amount)
    .sum()
    .orderBy('date').value();

Can you help me to fix it ? 你能帮我解决吗? Thanks. 谢谢。

You can just concat your year and month with groupBy and use it. 您可以使用groupBy来连接年份和月份并使用它。

var grouped = _.groupBy(data, function(i) {
  return new Date(i.date).getFullYear()+'-'+new Date(i.date).getMonth()
})

var resultUnsorted = _.map(t, (val, key) => ({key: key, val: val.reduce((p, c) => c.amount + p, 0) }));

then sort using _.orderBy 然后使用_.orderBy排序

const output = _.orderBy(resultUnsorted, 'key');

you can write your custom sort function using the behaviour you want. 您可以使用所需的行为编写自定义排序功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM