我想将从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图表。
答案 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()
'id'
分组,它将返回一个对象,其中键将
是唯一的ID,每个值将组成一个包含所有对象的数组
具有该ID 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>