按属性的Javascript组对象 [英] Javascript group objects by property

查看:92
本文介绍了按属性的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
     }
]

我正在尝试获得类似的东西:

And I'm trying to get something like:

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天全站免登陆