привязать первое значение свойства массива объекта к диаграмме. js - PullRequest
2 голосов
/ 29 марта 2020

У меня есть массив объектов, и вот как я присвоил ему значения.

  $("#gridview").click(function () {
            $("table tbody th").each(function () {
                var k = $(this).text().trim();
                keys.push(k);
            });
            $("table tbody tr").each(function (i, el) {
                var row = {}
                $.each(keys, function (k, v) {
                    row[v] = $("td:eq(" + k + ")", el).text().trim();
                });
                myData.push(row);
            });
            myData.shift()
            myData.length = 10

            console.log(myData);
        });

Вот так выглядит мой массив объектов в элементе inspect - console

enter image description here

как мне получить значения Регион и привязать его к меткам ниже:

 new Chart(document.getElementById("chart"), {
            type: 'horizontalBar',
            data: {
                labels: [I want to display all the region here],
                datasets: [{
                    label: "Android",
                    type: "horizontalBar",
                    stack: "Base",
                    backgroundColor: "#eece01",
                    data: ["I want to display ios user here"],
                }, {
                    label: "ios",
                    type: "horizontalBar",
                    stack: "Base",
                    backgroundColor: "#87d84d",
                    data: ["I want to display android user here"]
                }]
            },
            options: {
                scales: {
                    xAxes: [{
                        //stacked: true,
                        stacked: true,
                        ticks: {
                            beginAtZero: true,
                            maxRotation: 0,
                            minRotation: 0
                        }
                    }],
                    yAxes: [{
                        stacked: true,
                    }]
                },
            }
        }); 

FYI Я пытался myData [Region] но не работает

Ребята, я искал решения целый день, кажется, не могу найти, пожалуйста, помогите

1 Ответ

3 голосов
/ 29 марта 2020

Вы можете установить labels, используя .map() метод для myData массива, например:

data: {
   labels: myData.map(d => d.Region),
   ....
},

РЕДАКТИРОВАТЬ:

Вы можете создать новую функцию и добавить в нее весь код инициализации диаграммы, например:

function CreateChart() {
   new Chart(document.getElementById("chart"), {
      type: 'horizontalBar',
      data: {
         labels: myData.map(d => d.Region),
         ... you code here
      },
      ...
   });
}

CreateChart();

, а затем, нажав gridview, снова вызовите эту CreateChart функцию в конце, например:

$("#gridview").click(function() {
   // all your code logic here
   console.log(myData);
   CreateChart();
});
...