如何在“JavaScript”中使用`reduce`或`forEach`获取此数据格式?

时间:2018-01-16 09:46:43

标签: javascript arrays lodash

我有以下数据用于统计数据。

这是输入数据:

 data=[
       {  date: '2018-01-08',
         assignment: 'java',
         count: 2 },
       { date: '2018-01-04',
         assignment: 'java',
         count: 3 },
       { date: '2018-01-04',
         assignment: 'javaScript',
         count: 2 },
       { date: '2017-12-18',
         assignment: 'java',
         count: 2 },
       { date: '2017-11-24',
         assignment: 'java',
         count: 2 },
       { date: '2018-01-02',
         assignment: 'javaScript',
         count: 2 },....]

我的尝试:

let dataColln = data.map((e)=>{
   let obj = {};
   obj.date = e.date;
   obj[e.assignment] = e.count;
   return obj;
});

这是预期的输出:

 [{ 
     date:2018-01-08,
     java: 2
   },
   { 
     date:2018-01-04,
     java: 3,
     javaScript: 2
   },
   { 
     date:2018-01-02,
     javaScript: 2
   },...]

如何使用javaScript forEachreduce方法实现上述格式?

我能够获得分配给该名称的计数。 我还在lodash中尝试了groupByuniqBy方法。

1 个答案:

答案 0 :(得分:0)

您可以使用Map来收集值,并通过获取值来渲染结果。

此提案的功能



var data = [{ date: '2018-01-08', assignment: 'java', count: 2 }, { date: '2018-01-04', assignment: 'java', count: 3 }, { date: '2018-01-04', assignment: 'javaScript', count: 2 }, { date: '2017-12-18', assignment: 'java', count: 2 }, { date: '2017-11-24', assignment: 'java', count: 2 }, { date: '2018-01-02', assignment: 'javaScript', count: 2 }],
    map = new Map,
    result;

data.forEach(({ date, assignment, count }) =>
    map.set(date, Object.assign(map.get(date) || { date }, { [assignment]: count }))
);

result = [...map.values()]
    
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }