Lodash: convert array to angularjs nvd3 Multibarchart data

92 views Asked by At

i want to convert my apiArray fetched from api to AngularJS NVD3 MultiBarChart data format.

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

Using Lodash library where key is my id, to ->

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

Is there any solution? I want to feed my apiArray to AngularJS NVD3 to create Multibar chart.

2

There are 2 answers

0
Koushik Chatterjee On BEST ANSWER

you can simply use a _.groupBy with a _.map to acheive this

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

  1. First grouped by the 'id', it will return a object where keys will be unique ids and each values will a array contains all the objects having that id
  2. Then map it (each key/value) to a object have key key and values, key will contain the unique id and values will be the objects having that id (what we get in _.groupBy against each unique id, simple use that)

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>

0
Akrion On

This should help you:

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>

We are using chaining then grouping by (via groupBy) the id, then using entries to get the contents in an array form and then just map to the expected object result.