繁体   English   中英

如何使用函数更新Javascript对象

[英]How to update a Javascript object with a function

基本上,我有一个为Highchart图表定义一些属性的对象:

var options = {
    chart: {
        renderTo: 'container',
        type: 'line',
        marginRight: 130,
        marginBottom: 25
    },
    title: {
        text: 'Monthly Average Temperature',
        x: -20 //center
    },
    subtitle: {
        text: 'Source: WorldClimate.com',
        x: -20
    },
    xAxis: {
        categories: []
    },
    yAxis: {
        title: {
            text: 'Temperature (°C)'
        },
        plotLines: [{
            value: 0,
            width: 1,
            color: '#808080'
        }]
    },
    tooltip: {
        formatter: function () {
            return '<b>' + this.series.name + '</b><br/>' + this.x + ': ' + this.y + '°C';
        }
    },
    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'top',
        x: -10,
        y: 100,
        borderWidth: 0
    },
    series: [{
        name: 'Tokyo',
        data: aCosts
    }]
};

我想从文件(ajax调用)更新此对象,如下所示:

$.getJSON(
    "handler.php",
    function (oJSON) {
        var sName,
            sCost,
            aRow;
        for (sName in oJSON) {
            aRow = [];
            //categories = [];
            if (oJSON.hasOwnProperty(sName)) {
                aRow.push(sName);
                categories.push(sName);
            }
            // Create the chart
            var chart = new Highcharts.Chart(options);
        }
    }
);

问题是,我无法将新值传递给选项,因为它指出未定义类别。 我试过使用:

options.categories.push(sName)
options[categories].push(sName) 

而且没有工作。

如何更新选项对象中类别的值?

假设在$.JSON调用中可见options ,则此方法应该有效:

options.xAxis.categories.push( sName );

如果查看options对象的结构,则会看到categories位于属性xAxis下方。 因此,您应该这样解决。

您只需要像这样首先定义类别:

options.categories = [];

然后您可以将内容推送到该数组中。

编辑:您可以在json开头放置categories: []

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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