Lodash:将数组转换为 angularjs nvd3 Multibarchart 数据

Lodash: convert array to angularjs nvd3 Multibarchart data

我想将从 api 获取的 api 数组转换为 AngularJS NVD3 MultiBarChart 数据格式。

$scope.apiArray = [{"date":"2018-07-05T05:05:39.732Z","id":2"count":1},{"date":"2018-07-05T05:05:39.732Z","id": 3,"count": 1},"date": "2018-07-06T05:05:39.732Z","id": 2,"count": 1}, {"date": "2018-07-06T05:05:39.732Z","id": 4,"count": 2}

使用 Lodash 库,其中键是我的 id,到 ->

$scope.data = [{"key":"2", "values":[{"date": "2018-07-05T05:05:39.732Z", "count": "1"},{"date": "2018-07-06T05:05:39.732Z", "count": "1"}]},{"key":"3", "values":[{"date": "2018-07-05T05:05:39.732Z", "count": "1"}]},{"key":"4", "values":[{"date": "2018-07-06T05:05:39.732Z", "count": "2"}]}]

有什么解决办法吗?我想将我的 api 数组提供给 AngularJS NVD3 以创建多条形图。

这应该对您有帮助:

var data = [{ "date": "2018-07-05T05:05:39.732Z", "id": 2, "count": 1 }, { "date": "2018-07-05T05:05:39.732Z", "id": 3, "count": 1, }, { "date": "2018-07-06T05:05:39.732Z", "id": 2, "count": 1 }, { "date": "2018-07-06T05:05:39.732Z", "id": 4, "count": 2 } ]

const result = _(data)
   .groupBy(x => x.id)
   .entries()
   .map(x => ({ key: x[0], values: x[1]}))
   .value()
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

我们正在使用链接然后分组(通过 groupBy) the id, then using entries to get the contents in an array form and then just map 到预期的对象结果。

您可以简单地使用 _.groupBy_.map 来实现这个

_(data).groupBy('id').map((values, key) => ({key, values})).value()

  1. 首先按 'id' 分组,它将 return 一个对象,其中键将 是唯一的 ID,每个值将是一个包含所有对象的数组 有那个id
  2. 然后将它(每个key/value)映射到一个有键key and values的对象, 键将包含唯一 ID,值将是具有的对象 该 ID(我们在 _.groupBy 中针对每个唯一 ID 获得的内容,简单地使用它)

var data = [{ "date": "2018-07-05T05:05:39.732Z", "id": 2, "count": 1 }, { "date": "2018-07-05T05:05:39.732Z", "id": 3, "count": 1, }, { "date": "2018-07-06T05:05:39.732Z", "id": 2, "count": 1 }, { "date": "2018-07-06T05:05:39.732Z", "id": 4, "count": 2 } ];

var res = _(data)
          .groupBy('id')
          .map((values, key) => ({ key, values}))
          .value();
          
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>