使用lodash基于对象数组中的键添加或合并单个对象

时间:2017-11-17 06:40:47

标签: arrays lodash

我已经从数据库中的数据创建了一个对象数组。我想在饼图上绘制数据,但我在制作这种格式时遇到了困难。

以下是我到目前为止创建的最终结果:

let natinalityBreakdown = [
{Omani: Array(2), Pakistani: Array(2), Indian: Array(3), Test: Array(1)},
{Omani: Array(6), Chinese: Array(1)},
{Omani: Array(51), OMANi: Array(1), Pakistani: Array(5)}
];

使用以下代码:

let natinalityBreakdowna = [];
        _.forEach(company, function(company) {
          const linkedCompanyUsers= _(driver)
              .filter(d => d.companyId === company.companyId)
              .value();
           console.log(linkedCompanyUsers);
           let nationalityBreakdown = _.groupBy(linkedCompanyUsers, "nationality");
           console.log(nationalityBreakdown);
           nationalityBreakdown = _.omit(nationalityBreakdown, "undefined");
           console.log(nationalityBreakdown);
           natinalityBreakdowna.push(nationalityBreakdown);
        });
        console.log(natinalityBreakdowna);

我想在对象中输入如下结果:

{Omani: Array(59), Pakistani: Array(7), Indian: Array(3), Test: Array(1), Chinese: Array(1), OMANi: Array(1)}

由于

1 个答案:

答案 0 :(得分:1)

您可以使用array#reduce在对象中使用array#concat在同一组中添加相同国籍的人。

var result = natinalityBreakdown.reduce(function(res, obj){
  Object.keys(obj).forEach(function(k){
    res[k] = res[k] || [];
    res[k] = res[k].concat(obj[k]);
 });
 return res;
},{});