0

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.

  • 1
    This operation can be described as: "turning an object/dictionary into an array/sequence of key-value pairs". It can be done in a number of ways, the most C-forward is with a for..in (over the keys in the object) and Array.push. – user2864740 Jul 05 '16 at 16:31
  • Examples: http://stackoverflow.com/questions/25627889/converting-json-name-value-to-array-with-object-literals?lq=1 , http://stackoverflow.com/questions/34240678/converting-json-object-to-js-key-value-pairs-array?rq=1 , http://stackoverflow.com/questions/14615669/convert-objects-properties-and-values-to-array-of-key-value-pairs (except don't build a string) – user2864740 Jul 05 '16 at 16:34

1 Answers1

2

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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176