gafasmill gafasmill - 5 months ago 54
jQuery Question

Javascript / Json convert data format

I am reading data from a page which looks like this:

{"cars":0,"bikes":"1"}


In order to get the charts working in my page I need to convert it to something like this:

[{"key":"cars","value":0},{"key":"bikes","value":1}]


What would be the best way to convert this data, as this data can increase in size.

Answer

You can use map() and Object.keys() to do this

var obj = {"cars":0,"bikes":"1"};
var result = Object.keys(obj).map(function(e) {
  return {key: e, value: obj[e]}
});

console.log(result)