使用Lodash在Node.js中按多个字段分组

时间:2018-12-20 14:03:29

标签: javascript node.js lodash

我目前正在按帐户对数据进行分组,但也需要按销售人员进行分组。但是,我无法弄清楚如何成功实现该功能,以便同时按多个字段对它进行分组。有人可以为我提供一些指导吗?

这是我目前对数据进行分组的功能:

filteredData[rep.id] = _.chain(filteredData[rep.id]).groupBy('account').map(function(v, i) {
          return {
              customer: i,
              salesperson: _.reduce(v, function(res, val) {
                  return val['salesperson'];
              },0),
              sales_ytd: _.reduce(v, function(res, val) {
                  return res + Number(val['sales - ytd']);
              },0),
              mgn$_ytd: _.reduce(v, function(res, val) {
                  return res + Number(val['margin - ytd']);
              },0),
              sales_last: _.reduce(v, function(res, val) {
                  return res + Number(val['sales - pytd']);
              },0),
              mgn$_last: _.reduce(v, function(res, val) {
                  return res + Number(val['margin - pytd']);
              },0)
    }
}).value();

2 个答案:

答案 0 :(得分:1)

当您需要按多个字段分组时,需要合并字段值。

示例(未经测试):

filteredData[rep.id] = _(filteredData[rep.id])
  .groupBy(function(o) {
    return o.account + '-'  + o.salesperson;
  })
  .map(function(v, i) {
    var customer = _.head(_.words(i));

    return {
        customer: customer,
        salesperson: _.reduce(v, function(res, val) {
            return val['salesperson'];
        },0),
        sales_ytd: _.reduce(v, function(res, val) {
            return res + Number(val['sales - ytd']);
        },0),
        mgn$_ytd: _.reduce(v, function(res, val) {
            return res + Number(val['margin - ytd']);
        },0),
        sales_last: _.reduce(v, function(res, val) {
            return res + Number(val['sales - pytd']);
        },0),
    mgn$_last: _.reduce(v, function(res, val) {
        return res + Number(val['margin - pytd']);
    },0)
};

})。value();

答案 1 :(得分:0)

在没有输入数据和预期结果的情况下理解代码有点不清楚,但是,我相信您正在对数据进行分组并一次格式化结果。也许您可以考虑将函数编写的关注点分开:

const formatData = (object, index) => {
  return =  {
    customer: index,
    salesperson: _.reduce(object, function(res, val) {
        return val['salesperson'];
    },0),
    sales_ytd: _.reduce(object, function(res, val) {
        return res + Number(val['sales - ytd']);
    },0),
    mgn$_ytd: _.reduce(object, function(res, val) {
        return res + Number(val['margin - ytd']);
    },0),
    sales_last: _.reduce(object, function(res, val) {
        return res + Number(val['sales - pytd']);
    },0),
    mgn$_last: _.reduce(object, function(res, val) {
        return res + Number(val['margin - pytd']);
    },0)
  }
}

然后,您可以遍历分组分类列表并返回包含多个组的对象:

const groupFormatedDataBy = ( ...groupingClasses ) => {
  let output = {}
  grupingClasses.forEach(groupingClass => {

    output[groupingClass] = _.chain(filteredData[rep.id])
       .groupBy(groupingClass)
       .map( formatData )
       .value();

  })

  return output
}

PS:如果没有示例数据jejeje,我将无法测试代码,希望对您有帮助