Как добавить точки данных в динамическую c диаграмму на холсте JS, не зная, сколько данных нам нужно? - PullRequest
0 голосов
/ 06 марта 2020

Я хочу создать массив, который каким-то образом будет содержать все объекты без жесткого кодирования, сколько объектов я получил, что я хочу получить их данные, и я не совсем ясно объясню с помощью кода: `

    const localSavedCoins = getParsedToggledCurrencies(); // Brings JSON.parse array from localstorage which stores the name of the symbols.
    const firstData = []; // dataPoints
    const secondData = []; // dataPoints
    const thirdData = []; // dataPoints
    const fourthData = []; // dataPoints
    const fivthData = []; // dataPoints
    let addTextIfMissingDetails = [];


    const updateInterval = 2000;
    const dataLength = 20; // number of dataPoints visible at any point
    let addedSubtitles = false;
    localSavedCoins.forEach(coin => {
        const updateChart = function () {
            const date = new Date();
            let currentYear = date.getFullYear();
            let currentMonth = date.getMonth();
            let currentDay = date.getDate();
            let currentHour = date.getHours();
            let currentMinutes = date.getMinutes();
            let currentSeconds = date.getSeconds();

            $.ajax({
                url: `https://min-api.cryptocompare.com/data/pricemulti?fsyms=${coin}&tsyms=USD`,
                success: information => {

                    const chart = new CanvasJS.Chart("contentDiv", {
                        exportEnabled: true,

                        zoomEnabled: true,
                        zoomType: "xy",
                        toolTip: {
                            shared: true,
                        },
                        title: {
                            text: "Coin Price Graph In USD"
                        },

                        subtitles: addTextIfMissingDetails
                        ,
                        axisX: {

                            valueFormatString: "HH:mm:ss",
                            title: "Time"
                        },
                        axisY: {

                            includeZero: false,
                            title: "Price in USD",
                            titleFontColor: "#4F81BC",
                            lineColor: "#4F81BC",
                            labelFontColor: "#4F81BC",
                            tickColor: "#4F81BC"

                        },
                        data: [
                            {

                                type: "spline",

                                name: localSavedCoins[0],
                                showInLegend: true,
                                dataPoints: firstData
                            },
                            {
                                type: "spline",
                                name: localSavedCoins[1],
                                showInLegend: true,
                                dataPoints: secondData
                            },
                            {
                                type: "spline",
                                name: localSavedCoins[2],
                                showInLegend: true,
                                dataPoints: thirdData
                            },
                            {
                                type: "spline",
                                name: localSavedCoins[3],
                                showInLegend: true,
                                dataPoints: fourthData
                            },
                            {
                                type: "spline",
                                name: localSavedCoins[4],
                                showInLegend: true,
                                dataPoints: fivthData
                            },

                        ]
                    })
                    if (information[Object.keys(information)[0]].USD === undefined && !addedSubtitles) {
                        addTextIfMissingDetails.push({
                            text: "Note: There are coins that are missing information"
                        })
                        addedSubtitles = true;
                    }
                    if (coin === localSavedCoins[0]) {
                        firstData.push({
                            x: new Date(currentYear, currentMonth, currentDay, currentHour, currentMinutes, currentSeconds),
                            y: information[Object.keys(information)[0]].USD
                        });
                    }
                    if (coin === localSavedCoins[1]) {
                        secondData.push({
                            x: new Date(currentYear, currentMonth, currentDay, currentHour, currentMinutes, currentSeconds),
                            y: information[Object.keys(information)[0]].USD
                        });
                    }
                    if (coin === localSavedCoins[2]) {
                        thirdData.push({
                            x: new Date(currentYear, currentMonth, currentDay, currentHour, currentMinutes, currentSeconds),
                            y: information[Object.keys(information)[0]].USD
                        });
                    }
                    if (coin === localSavedCoins[3]) {
                        fourthData.push({
                            x: new Date(currentYear, currentMonth, currentDay, currentHour, currentMinutes, currentSeconds),
                            y: information[Object.keys(information)[0]].USD
                        });
                    }
                    if (coin === localSavedCoins[4]) {
                        fivthData.push({
                            x: new Date(currentYear, currentMonth, currentDay, currentHour, currentMinutes, currentSeconds),
                            y: information[Object.keys(information)[0]].USD
                        });
                    }

                    chart.render();


                },
                error: () => {
                    alert("Error getting graph.");
                }
            })
        }
        updateChart(dataLength);

        const intervalAjaxCalls = setInterval(function () { updateChart() }, updateInterval);`

Здесь я жестко запрограммировал, сколько объектов я получил (5), но что, если я хочу сделать так, чтобы клиент сохранял 100 объектов и отображал их на графике, не реально c жестко закодировать 100 таких объектов, Не удалось найти какой-либо другой способ сохранить в одном массиве данных все объекты, поэтому он будет без копирования кода.

Заранее спасибо, я предоставлю больше деталей, объяснение по мере необходимости.

...