让这个json进入正确的格式链变平groupby

时间:2016-08-07 16:04:13

标签: json format underscore.js

我已经尝试了很长时间才能完成这项工作但仍然无法回答我认为非常简单的事情,试图对类型进行分组和计算,我有这个:

[
  {
    "type": "TypeOne",
    "day": "2016-07-07"
  },
  {
    "type": "TypeOne",
    "day": "2016-07-07"
  },
  {
    "type": "TypeTwo",
    "day": "2016-07-07"
  },
  {
    "type": "TypeTwo",
    "day": "2016-07-08"
  },
  {
    "type": "TypeTwo",
    "day": "2016-07-08"
  },
  {
    "type": "TypeThree",
    "day": "2016-07-08"
  },
  {
    "type": "TypeThree",
    "day": "2016-07-09"
  },
  {
    "type": "TypeFour",
    "day": "2016-07-09"
  },
  {
    "type": "TypeTwo",
    "day": "2016-07-09"
  },
  {
    "type": "TypeThree",
    "day": "2016-07-09"
  },
  {
    "type": "TypeThree",
    "day": "2016-07-09"
  },
  {
    "type": "TypeFour",
    "day": "2016-07-09"
  }
]

我需要能够按日期计算Type的出现次数并将其转换为此结构:

[
  {
     "date":"2016-07-07"
    ,"TypeOne":2
    ,"TypeTwo":1
    ,"count":3
  },
  {
     "date":"2016-07-08"
    ,"TypeTwo":2
    ,"TypeThree":1
    ,"count":3
  },
  {
     "date":"2016-07-09"
    ,"TypeTwo":1
    ,"TypeThree":3
    ,"TypeFour":2
    ,"count":6
  }
]

我一直在尝试使用下划线,链,groupBy和map,但却无法实现。任何方向都表示赞赏。

1 个答案:

答案 0 :(得分:1)

只需迭代结构并聚合值:

var dates = [
  {
    "type": "TypeOne",
    "day": "2016-07-07"
  },
  {
    "type": "TypeOne",
    "day": "2016-07-07"
  },
  {
    "type": "TypeTwo",
    "day": "2016-07-07"
  },
  {
    "type": "TypeTwo",
    "day": "2016-07-08"
  },
  {
    "type": "TypeTwo",
    "day": "2016-07-08"
  },
  {
    "type": "TypeThree",
    "day": "2016-07-08"
  },
  {
    "type": "TypeThree",
    "day": "2016-07-09"
  },
  {
    "type": "TypeFour",
    "day": "2016-07-09"
  },
  {
    "type": "TypeTwo",
    "day": "2016-07-09"
  },
  {
    "type": "TypeThree",
    "day": "2016-07-09"
  },
  {
    "type": "TypeThree",
    "day": "2016-07-09"
  },
  {
    "type": "TypeFour",
    "day": "2016-07-09"
  }
];

var result = [];

dates.forEach(function(d) {
  var date = result.find(function(da) { return da.date === d.day; });
  if (!date) {
    date = { date: d.day, count: 0 };
    result.push(date);
  }
  
  date.count++;
  if(!date[d.type]) {
    date[d.type] = 1;
  } else {
    date[d.type]++;
  }
});

console.log(result);