1

Been searching online and tried a couple of fixes which haven't worked for me so was wondering if somebody else could help me sort this issue.

Basically I have attached some code to this which shows a function receiving a zone (zone is a number/there are only ever 3 zones 1,2,3). I then have 3 datasets called data1, data2, data3 which I want to reference using the zone number passed. But I need to keep data1, data2 & data3 all as separate arrays as they are then inserted into a chart (chartjs).

The function is called when the uses presses a switch on or off, there are 3 buttons one for each zone to enable that data set to show on the graph then when switched off it will remove that zones dataset.

Any help would be great, Kieran

    var data1 = [];
    var data2 = [];
    var data3 = [];

    // Adds/removes data sets from the chart
    function redrawChart(zone){
        var dataSet = "data"+zone;
        dataSet.push(7,8,8,9,10);

        historyChart = new Chart(document.getElementById('ns-popout-graph').getContext("2d")).Line(newData);
    }
1
  • in a browser, if conditions are right (i.e. those vars are declared in global scope), you can use dataSet = window['data' + zone] Commented Nov 22, 2015 at 22:32

1 Answer 1

1

You don't really have many options in this case. The cleanest one is to use object to hold arrays, then constructing dynamic key is easy:

var datas = {
    data1: [],
    data2: [],
    data3: []
};

// Adds/removes data sets from the chart
function redrawChart(zone) {

    var dataSet = datas["data" + zone];
    dataSet.push(7,8,8,9,10);

    // ...
}

Another approach could be eval but this is not recommended way to solve this problem. Note, that if data variables are defined in global namespace (window) you could still use window['data' + zone] but I hope you don't pollute global scope, do you? :)

Sign up to request clarification or add additional context in comments.

4 Comments

Only issue being I then have to add the arrays to this... in order to get them in the charts if you look at the history chart= line it adds this new data variable....
var newData = { labels : labels, datasets : [{ fillColor: "rgba(255, 0, 0, 0.0)", data : data1 }, { fillColor: "rgba(0, 255, 0, 0.0)", data : data2 }, { fillColor: "rgba(0, 0, 255, 0.0)", strokeColor: "lightblue", pointColor: "lightblue", pointStrokeColor: "rgba(0,0,0,0)", data : data3 }] };
You can still do it of course: data : datas.data1, data : datas.data1, etc.
Thanks!! really useful will tick as the answer in 5 mins when it lets me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.