Populate JavaScript Array from JSON Format

Viewed 81

Hi I have JSON data that looks like this:

[
  {"Mean of Arrivals for each hour":
     {"03-04":-35.62,"04-05":-3.62,"05-06":-3.7}
  }
]

I want to push it to an array, and have the array look like this:

[
{x: 03-04 y: -35.62},
{x: 04-05, y: -3.62},
{x: 05-06, y: -3.7}
]

Right now, it looks like the array below, and I don't know how to format it to look like above. Below is also the code I am using to populate the array. Would love some help on how to format the array.

[
x: {03-04: -35.62, 04-05: -3.62, 05-06: -3.7},
y: {03-04: -35.62, 04-05: -3.62, 05-06: -3.7}
]
var dataPoints = []; // final array with data

var chartData = new google.visualization.DataTable();
chartData.addColumn('string', 'Stunde');
chartData.addColumn('number', 'Ankunft');

function addData(data) {
    for (var i = 0; i < data.length - 1; i++) {
        dataPoints.push({
          x: data[i]["Mean of Arrivals for each hour"],
          y: data[i]["Mean of Arrivals for each hour"]
         });
    }

    dataPoints.forEach(function (row) {
        chartData.addRow([row.x, row.y]);
    });

    console.log(dataPoints);
    var chart = new google.charts.Bar(document.getElementById('plot3'));
    chart.draw(chartData, google.charts.Bar.convertOptions(options));
};

$.getJSON(url, addData);
3 Answers

Use a for...in loop to loop through the properties, construct the JSON and push to the array:

const data = [
  {"Mean of Arrivals for each hour":
     {"03-04":-35.62,"04-05":-3.62,"05-06":-3.7}
  }
]
const result = [], r = data[0]["Mean of Arrivals for each hour"];

for(const key in r) result.push({x: key, y: r[key]})

console.log(result);

This flattens everything out into a single array of data and then processes the objects through map(). It will accommodate any number of arrays inside the object, and any number of sets of coordinates inside those arrays.

let obj = [
  {"Mean of Arrivals for each hour":
     {"03-04":-35.62,"04-05":-3.62,"05-06":-3.7}
  }
]

let result = obj.map(Object.values).flat().map(Object.entries).flat().map(e => ({x:e[0], y:e[1]}))
console.log(result)

Iterate the Object.entries() of the sub objects in the array and create a new object for each of the entries

const data = [
  {"Mean of Arrivals for each hour":
     {"03-04":-35.62,"04-05":-3.62,"05-06":-3.7}
  }
]

const key = "Mean of Arrivals for each hour",
      res = [];

data.forEach(o => Object.entries(o[key]).forEach(([x, y]) => res.push({x, y})))

console.log(res)

Related