Javascript按属性对对象进行分组 [英] Javascript group objects by property

查看:38
本文介绍了Javascript按属性对对象进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按日期对数组中的对象进行分组:

I'm trying to group objects in an array by date:

var list = [
     {
         date: "2017-01-01",
         type: "type1",
         amount: 100
     },
     {
         date: "2017-01-01",
         type: "type2",
         amount: 150
     },
     {
         date: "2017-01-02",
         type: "type1",
         amount: 200
     }
]

我想得到类似的东西:

var dateArr = [
   {
      date: "2017-01-01",
      activities: [
        {
           type: "type1",
           amount: 100
        },
        {
           type: "type2",
           amount: 150
        }]
   }
]

我尝试了一些事情......像这样使用下划线(来自这里https://stackoverflow.com/a/15888912/4989305):

I have tried a few things...like this using underscore (from here https://stackoverflow.com/a/15888912/4989305):

var dateArr = _
.chain(list)
.groupBy('date')
.map(function(value, key) {
    return {
        date: key,
        activities: [{
            type: _.pluck(value, 'type'),
            amount: _.pluck(value, 'amount')
        }]
    }
})
.value();

我也试过这个(从这里https://stackoverflow.com/a/31373860/4989305)

I've also tried this (from here https://stackoverflow.com/a/31373860/4989305)

var dateArr = {};
list.forEach(function(item){
    dateArr[item.date] = dateArr[item.date]||[];
    dateArr[item.date].push(item);
});

但是,由于某种原因,两者都返回空.

But, for some reason both return empty.

任何帮助将不胜感激.

推荐答案

几行现代 JavaScript 就能得到你想要的结果:

A few lines of modern JavaScript will get you the result you want:

var dateArr = Object.values(list.reduce((result, {
    date,
    type,
    amount
}) => {
    // Create new group
    if (!result[date]) result[date] = {
        date,
        activities: []
    };
    // Append to group
    result[date].activities.push({
        type,
        amount
    });
    return result;
}, {}));

说明:

  1. 使用Array.reduce 将列表合并为一组结果,一个简单的对象,按日期分组.
  2. 合并功能解构项目分成三个参数.
  3. 然后它会在必要时创建一个新组.
  4. 然后将当前项目的类型和数量作为 对象字面量.
  5. 同一个集合返回给reduce,以便下一个项目合并到同一个集合中.
  6. 使用Object.values 从集合中提取值.(放下钥匙)
  1. Use Array.reduce to consolidate the list into a set of results, a plain object, grouped by date.
  2. The consolidate function destructure the item into three parameters.
  3. It then creates a new group if necessary.
  4. Current item's type and amount is then pushed to the group as part of an object literal.
  5. The same set is returned to the reduce, so that the next item will consolidate into the same set.
  6. Use Object.values to extract the values from the set. (Drop the keys)

这篇关于Javascript按属性对对象进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆