Lodash group by multiple properties if property value is true

前端 未结 8 1932
执笔经年
执笔经年 2020-12-10 02:20

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 mod

8条回答
  •  无人及你
    2020-12-10 02:49

    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': [ ..., ... ] } }
    

提交回复
热议问题