Nigel Nigel - 3 months ago 7
JSON Question

Getting this json into the correct format chain flatten groupby

I have been trying for ages to make this work and still have no answer to something that I thought would be quite straightforward, trying to group and count types, I have this:

[
{
"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"
}
]


I need to be able to count the occurrences of Type by the date and turn it into this structure:

[
{
"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
}
]


I've been trying to make it work with underscore, chain, groupBy and map, just not able to make it happen. Any direction is appreciated.

Answer

Here's a solution using underscore's countBy function to count the types after grouping by day:

var result = _.chain(data)
    .groupBy('day')
    .map( (grp, date) => _.extend( { date: date }, _.countBy(grp,'type')))
    .value()

	var data = [
	  {
	    "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 = _.chain(data)
		.groupBy('day')
		.map( (grp, date) => _.extend( { date: date }, _.countBy(grp,'type')))
		.value()
	
    
    document.getElementById('result').textContent = JSON.stringify(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>

<p>
  <pre id="result"></pre>
</p>

Comments