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

时间:2018-10-01 15:39:32

标签: angularjs lodash nvd3.js angularjs-nvd3-directives

我想将从api获取的apiArray转换为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库->

$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"}]}]

有什么解决办法吗?我想将apiArray喂入AngularJS NVD3以创建Multibar图表。

2 个答案:

答案 0 :(得分:0)

这应该对您有帮助

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)对ID进行分组,然后使用entries以数组形式获取内容,然后仅map即可得到预期的对象结果。

答案 1 :(得分:0)

您可以简单地将_.groupBy_.map配合使用

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

  1. 首先按'id'分组,它将返回一个对象,其中键将 是唯一的ID,每个值将组成一个包含所有对象的数组 具有该ID
  2. 然后将其(每个键/值)映射到具有键key and values的对象, 键将包含唯一的ID,值将是具有 该ID(我们可以根据每个唯一ID在_.groupBy中得到什么,简单使用即可)

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>