Reputation: 83
I'm having trouble getting the output I need from the following json
[
{"Type":"A","Location":"1"},
{"Type":"A","Location":"2"},
{"Type":"A","Location":"3"},
{"Type":"B","Location":"2"},
{"Type":"B","Location":"3"},
{"Type":"C","Location":"1"},
{"Type":"A","Location":"1"},
{"Type":"A","Location":"1"},
{"Type":"A","Location":"3"},
{"Type":"C","Location":"1"},
{"Type":"C","Location":"1"},
{"Type":"C","Location":"1"}
]
my expected output is as follows:
[
{"Type":"A","Count":"6","Locations":
[
{"Location":"1","Count":"3"},
{"Location":"2","Count":"1"},
{"Location":"3","Count":"2"}
]
},
{"Type":"B","Count":"2","Locations":
[
{"Location":"2","Count":"1"},
{"Location":"3","Count":"1"}
]
},
{"Type":"C","Count":"4","Locations":
[
{"Location":"1","Count":"4"}
]
}
]
The code I have so far will group the locations and give me the counts, but I'm stuck with the inner group
var result = _.chain($scope.incidents)
.groupBy("Type")
.map(function(value,key){
return{
Type:key,
Count:value.length
}
}).value();
Upvotes: 2
Views: 1019
Reputation: 21209
Try this:
var result = _.chain($scope.incidents).groupBy('Type').map(function(value, key) {
return {
Count: value.length,
Type: key,
Locations: _.chain(value).groupBy('Location').map(function(value, key) {
return {
Location: key,
Count: value.length
};
}).value()
};
}).value();
Upvotes: 2
Reputation: 1550
I'm assuming you're using Lo-Dash, as underscore didn't seem to have the groupBy(<string>)
feature.
In any case, here's a solution:
var result = _(list)
.groupBy('Type')
.map(function (locations, type) {
return {
Type: type,
Count: locations.length,
Locations: _(locations)
.groupBy('Location')
.map(function (arr, location) {
return {
Count: arr.length,
Location: location
};
}).value()
};
}).value();
Upvotes: 2