pmirnd pmirnd - 3 months ago 10
Javascript Question

Javascript push JSON to Array (Highcharts)

I have this empty array:

var seriesGraficos =[];


and this already made vars:

var dataEnergiaContratadaA = [1458, 1332, 777];
var dataDemandaA = [18, 13, 77];
var nameEnergiaContratadaA = "Energy";
var nameDemandaA = "Demand";


and I need to fill the array like this way (I need the seriesGraficos exactly like this, it's the series array of Highcharts):

seriesGraficos = [{
name: nameEnergiaContratadaA,
data: dataEnergiaContratadaA
}, {
name: nameDemandaA ,
data: dataDemandaA
}];


I was trying something like:

seriesGraficos.push(
{"name": nameEnergiaContratadaA,"data": dataEnergiaContratadaA},
{"name": nameDemandaA,"data": dataDemandaA}
);


But I can't get it. Any help?

Answer

You can do this in ES6 with spread operator :

seriesGraficos = [];
seriesGraficos.push(...[
{"name": 'nameEnergiaContratada',"data": 'dataEnergiaContratadaA'},
{"name": 'nameDemandaA',"data": 'dataDemandaA'}
]);

console.log(seriesGraficos);