Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  153] [ 7]  / answers: 1 / hits: 78397  / 8 Years ago, wed, october 19, 2016, 12:00:00

I have an array of vehicles that need to be grouped by make and model, only if the 'selected' property is true. The resulting object should contain properties for make model and count. Using lodash, how can I organize the vehicle objects into the desired result objects. I'm able to get the vehicle objects grouped by makeCode but I'm not sure how to group by more than one property.



group by make code works



      var vehicles = _.groupBy(response.vehicleTypes, function(item)
{
return item.makeCode; // how to group by model code as well
});


initial vehicles



{
id: 1,
selected: true,
makeCode: Make-A,
modelCode: Model-a,
trimCode: trim-a,
yearCode: 2012
},
{
id: 2,
selected: false,
makeCode: Make-A,
modelCode: Model-a,
trimCode: trim-a,
yearCode: 2013
},
{
id: 3,
selected: true,
makeCode: Make-B,
modelCode: Model-c,
trimCode: trim-a,
yearCode: 2014
},
{
id: 25,
selected: true,
makeCode: Make-C,
modelCode: Model-b,
trimCode: trim-b,
yearCode: 2012
},
{
id: 26,
selected: true,
makeCode: Make-C,
modelCode: Model-b,
trimCode: trim-a,
yearCode: 2013
}


result object



{
Make-A: {
Model-a: {
count: 1
}
}
},

{
Make-B: {
Model-c: {
count: 1
}
}
},
{
Make-C: {
Model-b: {
count: 2
}
}
}

More From » lodash

 Answers
67

Since you're already using lodash, you can take advantage of the _.filter function. This will return only the items where selected is true.



var selectedVehicles = _.filter(response.vehicleTypes, 'selected');


Now that you have the selectedVehicles array, you can use your original code for grouping by the makeCode.



selectedVehicles = _.groupBy(selectedVehicles, function(item) {
return item.makeCode;
});


This returns an object, so we will need to iterate through those keys, and perform our second groupBy



_.forEach(selectedVehicles, function(value, key) {
selectedVehicles[key] = _.groupBy(selectedVehicles[key], function(item) {
return item.modelCode;
});
});


From this you will have an object of the form. I'll leave it to you to get the count from each array.



{ 'Make-A': { 'Model-a': [ ... ] },
'Make-B': { 'Model-c': [ ... ] },
'Make-C': { 'Model-b': [ ..., ... ] } }

[#60339] Monday, October 17, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckinleykeyshawnb

Total Points: 281
Total Questions: 99
Total Answers: 111

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;