Lodash groupby对象和组合数组

时间:2017-03-28 04:39:02

标签: javascript lodash

我的日历数据类似于

[ 
  { 
    date: 1488128400000,
      details: [ 
        { time: '01.00 - 02.00', title: 'go sleep' } 
      ] 
  },
  { 
    date: 1488128400000,    
      details: [ 
        { time: '05.30 - 06.30', title: 'wakeup' } 
      ]
  },
  { 
    date: 1488301200000,
      details: [ 
        { time: '09.00 - 10.00', title: 'go to school' } 
    ]   
  } 
]

我想将相同的日期分组并合并每个细节数组,如此

[ 
  { 
    date: 1488128400000,
      details: [ 
        { time: '01.00 - 02.00', title: 'go sleep' },
        { time: '05.30 - 06.30', title: 'wakeup' } 
      ] 
  },
  { 
    date: 1488301200000,
      details: [ 
        { time: '09.00 - 10.00', title: 'go to school' } 
    ]   
  } 
]

我可以用 Lodash解决这个问题吗?

我刚刚研究过Lodash,我不知道这个案例,也不知道搜索这个案例的关键词。

谢谢

2 个答案:

答案 0 :(得分:1)

您无需使用lodash。以下内容实现了您的目标。虽然您可能需要一些polyfill,具体取决于您所需的浏览器支持。 https://jsbin.com/sojarabiqi/edit?js,console

const events = [ 
  { 
    date: 1488128400000,
    details: [ 
      { time: '01.00 - 02.00', title: 'go sleep' } 
    ] 
  },
  { 
    date: 1488128400000,    
    details: [ 
      { time: '05.30 - 06.30', title: 'wakeup' } 
    ]
  },
  { 
    date: 1488301200000,
    details: [ 
      { time: '09.00 - 10.00', title: 'go to school' } 
    ]   
  } 
];

const grouped = events.reduce(function (grouped, event) {
  // Attempt to find existing grouped date
  const index = grouped.findIndex(function (date) {
    return date.date === event.date;
  });

  // Append event details to existing date 
  if (index !== -1) {
    grouped[index]['details'].push(event.details[0]);
  }
  // Append event details to new date
  else {
    grouped.push(event);
  }  

  return grouped;
}, []);

console.log(grouped);

答案 1 :(得分:0)

我试着在没有lodash的情况下解决你的问题。希望我帮助你。

var data =  [ 
  { 
    date: 1488128400000,
      details: [ 
        { time: '01.00 - 02.00', title: 'go sleep' } 
      ] 
  },
  { 
    date: 1488128400000,    
      details: [ 
        { time: '05.30 - 06.30', title: 'wakeup' } 
      ]
  },
  { 
    date: 1488301200000,
      details: [ 
        { time: '09.00 - 10.00', title: 'go to school' } 
    ]   
  } 
];

for(var i=0; i< data.length; i++){
    for(var j = i+1; j<data.length ; j++){
    if(data[i].date == data[j].date){
                for(var k = 0; k < data[j].details.length; k++){
            data[i].details.push(data[j].details[k]);
        }
        data.splice(j,1);
    }
  }
}

console.log(data);