Highcharts远程数据 - JSON对象未定义

问题描述 投票:1回答:1

我试图呈现从MySQL数据Highcharts柱形图 - > json_encode() - >的getJSON()。的95%的时间有6行要处理的数据,因此这可以容易地通过手动环和图表呈现细。问题是,当有结果数组中偶尔少行 - 我当然看到类型错误:未定义在这些情况下无法读取属性“名”。我工作的代码:

$.getJSON(url, function(json)) {
    if(typeof json === 'object' && json.length > 0) {
        var nameData = [json[0]['name'],json[1]['name'],json[2]['name'],json[3]['name'],json[4]['name'],json[5]['name']];

        var matchedData = [json[0]['data']['Matched'],json[1]['data']['Matched'],json[2]['data']['Matched'],json[3]['data']['Matched'],json[4]['data']['Matched'],json[5]['data']['Matched']];

        var bookedData = [json[0]['data']['Booked'],json[1]['data']['Booked'],json[2]['data']['Booked'],json[3]['data']['Booked'],json[4]['data']['Booked'],json[5]['data']['Booked']];
    }
    var options = {
        chart: {
            renderTo: 'div',
            type: 'column'
        },
        title: {
            text: 'Chart Title',
            x: -20
        },
        xAxis: {
            type: 'category',
            categories: nameData,
            crosshair: true
        },
        series: [{
            name: 'Matched',
            data: matchedData
        }, {
            name: 'Booked',
            data: bookedData
        }]
    }
    chart = new Highcharts.Chart(options);
}

这个正确呈现图表。然而,当有比阵列中的通常的6项越少,类型错误停止的事情。我尝试这之前,发送到Highcharts统计数组项目:

var nameData = [];
var matchedData = [];
var bookedData = [];
if (typeof json === 'object' && json.length > 0) {
    for (var a = 0; a < json.length; a++) {
        nameData += [json[a]['name']+","];
        matchedData += [json[a]['data']['Matched']+","];
        bookedData += [json[a]['data']['Booked']+","];
    }
}

这个警报()从相同的结果手动创建的数组,但没有呈现在图表上。需要改变什么?

javascript arrays highcharts getjson undefined-behavior
1个回答
1
投票

试着在你的数据映射。您可以使用map功能真的很容易设置应有尽有。这是一个很多清洁和更简单的为好。你可以找到map here参考。

$.getJSON(url, function(json)) {
    if(typeof json === 'object' && json.length > 0) {
        var nameData = json.map(obj => obj['name']);

        var matchedData = json.map(obj => obj['data']['Matched']);

        var bookedData = json.map(obj => obj['data']['Booked']);
    }
    var options = {
        chart: {
            renderTo: 'div',
            type: 'column'
        },
        title: {
            text: 'Chart Title',
            x: -20
        },
        xAxis: {
            type: 'category',
            categories: nameData,
            crosshair: true
        },
        series: [{
            name: 'Matched',
            data: matchedData
        }, {
            name: 'Booked',
            data: bookedData
        }]
    }
    chart = new Highcharts.Chart(options);
}
© www.soinside.com 2019 - 2024. All rights reserved.