Denish Denish - 4 months ago 13
Javascript Question

Javascript: Transform array of object response via lodash or underscore or corejavascript

I am working with highChart to create a column chart. Any how I reached to creating following arrayofObj via communicating with database.

Now, I require to transform following

source
array of object to below output.

var source = [
{data: 258, name: '2014'}
{data: 18, name: '2016'}
{data: 516, name: '2014'}
{data: 0, name: '2014'}
{data: 354, name: '2014'}
{data: 18, name: '2016'}
]`


Convert this array of object to

Output

[{
name: '2014',
data: [258, 516, 354]
}, {
name: '2016',
data: [18, 0, 18]
}]


Basically, I want my array to group by name (year) and data should be in array

Here is the solutions which i have applied.

var source = [];
_.each(source, function(singlerec) {
source.push({
name: singlerec.name,
data: singlerec.data // Here It only assign single record
});
});

Answer

In Lodash, I always use _.groupBy and then _.map to the output format.

var source = [{"data":258,"name":"2014"},{"data":18,"name":"2016"},{"data":516,"name":"2014"},{"data":0,"name":"2014"},{"data":354,"name":"2014"},{"data":18,"name":"2016"}];

var output = _(source)
  .groupBy('name')
  .map(function(v, k) { return { name: k, data: _.map(v, 'data') } })
  .value();

console.log(output);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

Comments