简体   繁体   中英

Pass dynamic variables in options to Google Charts

I am trying to pass a Series number in a Google Chart option through a variable. However it is not accepting it as a variable and instead is taking it as a string. You can see in Image1 that I have passed in Series parameter SecondseriesColumnNumber as a variable and value is 1.

Image 1 图片1

However in the output it is considering it as a string but not as the series number as shown below

Image 2

在此处输入图片说明

Other parameters are considering the values correctly but not the series one. How can I make this work? My code is below

var options = {
    title: title,
    width: width,
    height: height,
    bar: { groupWidth: '75%' },
    chartArea: { left: "8%", right: "8%", top: "10%", width: "100%", height: "75%" },
    backgroundColor: 'transparent',
    tooltip: { textStyle: { color: 'black' }, isHtml: true },
    isStacked: isStacked,
    seriesType: seriesType,
    series: { SecondseriesColumnNumber: { type: SecondseriesType } },
    hAxis: { slantedText: true }
};

var chart = new google.visualization.ComboChart($('DivSeries')[0]);

the problem has to do with JavaScript syntax.
you are not able to use a variable as a key in the definition of an object.
you must first create the object, then you can add additional keys using variables.

there are two ways to get / set values of object keys, once the object is defined.
both of the following will return the same value for title.

var title = options.title;
var title = options['title'];

where as in the latter, we can substitute a variable for the title key.

var key = 'title';
var title = options[key];

in this case, define the static options as needed.

var options = {
    title: title,
    width: width,
    height: height,
    bar: { groupWidth: '75%' },
    chartArea: { left: "8%", right: "8%", top: "10%", width: "100%", height: "75%" },
    backgroundColor: 'transparent',
    tooltip: { textStyle: { color: 'black' }, isHtml: true },
    isStacked: isStacked,
    seriesType: seriesType,
    series: {},
    hAxis: { slantedText: true }
};

then you can use a variable to further define the series option.

var SecondseriesColumnNumber = 1;
options.series[SecondseriesColumnNumber] = { type: SecondseriesType };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM