Want to split one single JSON objects to multiple JSON objects using Javascript

Deena P picture Deena P · May 10, 2016 · Viewed 15.2k times · Source

I have a JSON response like below,

[{label: "8", value: "1", value2: "0", value3: "0"},{label: "9", value: "7", value2: "2", value3: "6"},{label: "10", value: "12", value2: "1", value3: "0"},…]

Now I want to split it into 4 JSON objects for each key, like below.

[{label: "8"},{label: "9"},{label: "10"},…]
[{value: "1"},{value: "7"},{value: "12"},…] 
[{value2: "0"},{value2: "2"},{value2: "1"},…] and more

I tried below things but wasn't successful.

Try1:

var o2 = { uhash: o.uhash };
delete o.uhash;

Try2:

Using for loop to get each pair, array.push and JSON.stringigy() method.

All I want to is create a stacked fusioncharts using the JSON response from database

Answer

omarjmh picture omarjmh · May 10, 2016

You could make a function that returns the array you want: You could then map through and call this on the properties in your JSON:

function makeArray(value) {
  return j.map(function(a) {
    return {[value]: a[value]};
  });
}

var labels = makeArray('label');

Working Example