简体   繁体   English

“无法读取未定义的属性'xyz':如何在数字json上使用map或foreach?

[英]“Cannot read property 'xyz' of undefined”: How to use map or foreach on numeric json?

I'm trying to automatically generate a chart provided by ChartJs, but I cannot seem to get it to work. 我正在尝试自动生成ChartJs提供的图表,但我似乎无法让它工作。 I'm generating a .json-file with all the neccessarry information, which contains names and numbers (tournament winners and their amount of wins in this case) from the database, which is generated by a PHP-file. 我正在生成一个包含所有必要信息的.json文件,其中包含数据库中的名称和数字(锦标赛获胜者及其在此情况下的获胜数量),该数据库由PHP文件生成。 My code at the current stage just throws me a "Cannot read property 'players' of undefined" error in the console. 我在当前阶段的代码只是在控制台中抛出一个“无法读取未定义的属性'玩家'错误”错误。

My problem here is, that I don't quite know, how to loop through my elements here? 我的问题是,我不太清楚,如何在这里循环我的元素?

I tried it with map and forEach, but neither seem to work. 我用map和forEach尝试过,但似乎都没有用。 Adding "JSON_FORCE_OBJECT" to json_encode at least provided numbers to the array. 将“JSON_FORCE_OBJECT”添加到json_encode至少为数组提供了数字。

Main code for ChartJs: ChartJs的主要代码:

<script>
    $.getJSON('https://DOMAIN/-chartjs-data.json', function(jsonfile) {

    var labels = jsonfile.data.final_rank_1.players.forEach((player) => {
        return player.username;
    });
    var data = jsonfile.data.final_rank_1.players.forEach((player) => {
        return player.wins;
    });

    var ctx = canvas.getContext('2d');
    var config = {
       type: 'line',
       data: {
          labels: labels,
          datasets: [{
             label: 'Graph Line',
             data: data,
             backgroundColor: 'rgba(0, 119, 204, 0.3)'
          }]
       }
    };

    var chart = new Chart(ctx, config);
    });
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<canvas id="canvas"></canvas>

Beginning of the json: json的开头:

{
"data": [
{
"final_rank_1": {
"players": {
"0": {
"0": "Jens",
"1": "22",
"username": "Jens",
"wins": "22"
},
"1": {
"0": "Hand",
"1": "17",
"username": "Hand",
"wins": "17"
},
"2": {
"0": "Hund",
"1": "5",
"username": "Hund",
"wins": "5"
},
"3": {
"0": "Hey",
"1": "3",
"username": "Hey",
"wins": "3"
},

Changing 更改

var labels = jsonfile.data.final_rank_1.players.forEach((player) => {
        return player.username;
    });
    var data = jsonfile.data.final_rank_1.players.forEach((player) => {
        return player.wins;
    });

to

var labels = jsonfile.data[0].final_rank_1.players.map(function(player) {
        return player.username;
    });
    var data = jsonfile.data[0].final_rank_1.players.map(function(player) {
        return player.wins;
    });

resolved my issue. 解决了我的问题。 Knowing what an object is and what an array is, is really helpful. 了解对象是什么以及数组是什么,确实很有帮助。

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

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