How to convert JSON to array to column chart in google Charts?

Asked

Viewed 425 times

0

I have a JSON in the following format:

[
  {
    "Pais": "Qatar",
    "Valor": 683900
  },
  {
    "Pais": "Luxembourg",
    "Valor": 519360
  },
  {
    "Pais": "Iceland",
    "Valor": 476710
  },
  {
    "Pais": "Bahrain",
    "Valor": 442990
  },
  {
    "Pais": "United States",
    "Valor": 415570
  }
]

I want to use that JSON to popular the chart data as in the example below, but how can I convert it to array and use the google.visualization.arrayToDataTable to load the data?

google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);

function drawStuff() {
	var data = new google.visualization.arrayToDataTable([
		['Nome', 'Valor'],
    ["Qatar", 683900],
		["Luxembourg", 519360],
		["Iceland", 476710],
		["Bahrain", 442990],
		["United States", 415570]
	]);

	var options = {
		width: 800,
		legend: { position: 'none' },
		chart: {
			title: 'Top 5',
			subtitle: 'Uso de energia por país'
		},
		axes: {
			x: {
				0: { side: 'top' } // Top x-axis.
			}
		},
		bar: { groupWidth: "90%" }
	};

	var chart = new google.charts.Bar(document.getElementById('top_x_div'));
	// Convert the Classic options to Material options.
	chart.draw(data, google.charts.Bar.convertOptions(options));
};
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  </head>
  <body>
    <div id="top_x_div" style="width: 800px; height: 600px;"></div>
  </body>
</html>

FIDDLE.

2 answers

1


Use the function map to traverse the array, passing a function that receives the value of the indexes and returns the new value

const data = [
  {
    "Pais": "Qatar",
    "Valor": 683900
  },
  {
    "Pais": "Luxembourg",
    "Valor": 519360
  },
  {
    "Pais": "Iceland",
    "Valor": 476710
  },
  {
    "Pais": "Bahrain",
    "Valor": 442990
  },
  {
    "Pais": "United States",
    "Valor": 415570
  }
];

const dataAsArray = [
  data.map(value => value.Pais),
  data.map(value => value.Valor)
];

console.log(dataAsArray);

  • Thanks for the help, but the format was not correct. I got it the way I posted in my reply.

  • I edited the answer I thought that was the format I wanted

  • Great, it was exactly the same format as what I did but with a more elegant code! + 1 :D

1

I converted using arrays.map as an example below:

const data = [
  {
    "Pais": "Qatar",
    "Valor": 683900
  },
  {
    "Pais": "Luxembourg",
    "Valor": 519360
  },
  {
    "Pais": "Iceland",
    "Valor": 476710
  },
  {
    "Pais": "Bahrain",
    "Valor": 442990
  },
  {
    "Pais": "United States",
    "Valor": 415570
  }
];

var arrays = ['Pais', 'Valor'];
arrays = arrays.map(function (campo) {
	var novoConteudo = data.map(function (objeto) {
		return objeto[campo];
	});
	return novoConteudo;
});

console.log(arrays);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.