AngularJS 为多条形图 NVD3 准备数据

AngularJS prepare data for MultiBar Chart NVD3

我正在调用我的 API 以获得下面的 JSON 数组,

array = [{"date":1533791167870,"count":1,"name":"James"},{"date":1533791167870,"count":3,"name":"Kane"},{"date":1533791167918,"count":1,"name":"Kane"},{"date":1536203856526,"count":2,"name":"Trent"},{"date":1536217871371,"count":5,"name":"Kane"},{"date":1536217882525,"count":4,"name":"James"}]

还有我的名字数组,

name_array = ["Kane","Trent","James","Sam"]

我正在使用 Lodash 库。我想得到我的输出数组,这样对于每个日期,所有名称都从 name_array 映射,如果有计数,则从数组中获取计数值,否则为 0。我期望我的输出数组如下 result_array ,

    result_array = [{
    "date": 1533791167870,
    "count": 1,
    "name": "James"
  }, {
    "date": 1533791167870,
    "count": 3,
    "name": "Kane"
  },
  {
    "date": 1533791167870,
    "count": 0,
    "name": "Trent"
  },
  {
    "date": 1533791167870,
    "count": 0,
    "name": "Sam"
  }, {
    "date": 1533791167918,
    "count": 0,
    "name": "James"
  },
  {
    "date": 1533791167918,
    "count": 1,
    "name": "Kane"
  },
  {
    "date": 1533791167918,
    "count": 0,
    "name": "Sam"
  },
  {
    "date": 1533791167918,
    "count": 0,
    "name": "Trent"
  }, {
    "date": 1536203856526,
    "count": 0,
    "name": "James"
  },
  {
    "date": 1536203856526,
    "count": 0,
    "name": "Kane"
  },
  {
    "date": 1536203856526,
    "count": 2,
    "name": "Trent"
  },
  {
    "date": 1536203856526,
    "count": 0,
    "name": "Sam"
  }, {
    "date": 1536217871371,
    "count": 0,
    "name": "James"
  },
  {
    "date": 1536217871371,
    "count": 5,
    "name": "Kane"
  },
  {
    "date": 1536217871371,
    "count": 5,
    "name": "Trent"
  },
  {
    "date": 1536217871371,
    "count": 5,
    "name": "Sam"
  }, {
    "date": 1536217882525,
    "count": 4,
    "name": "James"
  },
  {
    "date": 1536217882525,
    "count": 0,
    "name": "Trent"
  }, {
    "date": 1536217882525,
    "count": 0,
    "name": "Sam"
  },
  {
    "date": 1536217882525,
    "count": 0,
    "name": "Kane"
  }
]

我正在为 NVD3 AngularJS MultiBar 图表这样做。由于我的数组数据不适用于堆叠视图,但组视图工作正常。 我正在使用 AngularJS、Lodash。

非常感谢您的帮助。

您可以通过多次 _.map 调用来完成此操作:

let result = _.flatten(_.map(_.groupBy(array, 'date'), (existedEntries, date) => {
  let usedNames = _.map(existedEntries, entry => entry.name);
  let namesDiff = _.difference(name_array, usedNames);
  let dateNumeric = parseFloat(date);
  let enrichedNames = _.map(namesDiff, name => {
    return {
      date: dateNumeric,
      count: 0,
      name: name
    };
  });
  return _.union(existedEntries, enrichedNames);
}));

首先,我们按日期对现有条目进行分组,并为每个组确定在那里使用的名称。然后我们计算所有可能的名字和组中使用的名字之间的差异。对于差异中的每个名称,我们将其映射到默认对象,count: 0date 等于当前现有组的日期。接下来,我们将组的现有值与丰富名称差异后获得的值结合起来。最终 flatten 调用删除了时间内部数组结构。

如果您使用 ES5 或更低版本,请将箭头语法糖替换为函数,并将 let 替换为 var,即 var usedNames = _.map(existedEntries, function(entry) {return entry.name;});

P.S。在 ES6 中,你可以用同名的原生函数替换 Lodash map 函数,即 let usedNames = existedEntries.map(entry => entry.name);