Tim-Tim Tim-Tim - 2 months ago 4
JSON Question

How convert json in array by JS

I need to convert JSON data from

[{"Date":"2014","Amount1":90,"Amount2":800}, {"Date":"2015","Amount1":110,"Amount2":300},{"Date":"2016","Amount1":3000,"Amount2":500}]


to

[['Date', 'Amount1', 'Amount2'],
['2014', 90, 800],
['2015', 110, 300],
['2016', 3000, 500]]


How can I do it?

Answer

Use Array#reduce and Array#map methods.

var data = [{
  "Date": "2014",
  "Amount1": 90,
  "Amount2": 800
}, {
  "Date": "2015",
  "Amount1": 110,
  "Amount2": 300
}, {
  "Date": "2016",
  "Amount1": 3000,
  "Amount2": 500
}];

// iterate over the array value
var res = data.reduce(function(arr, o) {
  // push the new value to array
  arr.push(
    // generate object value array using the key array
    arr[0].map(function(k) {
      // return the property value
      return o[k]
    })
  );
  // return the updated array
  return arr;
  // set initial variable as array with
  // fist element as object property array
}, [Object.keys(data[0])]);

console.log(res);

Comments