Mam problem z uzyskaniem wyjścia, którego potrzebuję z następujących 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"}
]
Moja oczekiwana wydajność jest następująca:
[
{"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"}
]
}
]
Kod, którego do tej pory mam do tej pory, będzie grupować lokalizacje i dać mi liczy, ale utknąłem z grupą wewnętrzną
var result = _.chain($scope.incidents)
.groupBy("Type")
.map(function(value,key){
return{
Type:key,
Count:value.length
}
}).value();
2
user3918569
14 sierpień 2014, 00:43
2 odpowiedzi
Najlepsza odpowiedź
Spróbuj tego:
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();
2
tcooc
13 sierpień 2014, 21:04
Zakładam, że używasz Lo-Dash, ponieważ podkreślenie nie wydaje się mieć funkcji groupBy(<string>)
.
W każdym razie, oto rozwiązanie:
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();
2
Patrik Oldsberg
13 sierpień 2014, 20:59