kevinabraham kevinabraham - 3 months ago 8
Ajax Question

How to escape a variable with a '.' in jquery/javascript?

Im using ajax to make a request. As part of the request I get an ID which is in an nested json. Like so:

{"id": 1,"point": ["2016-10-13 09:05:53",85],"id": 1,"point": ["2016-10-13 09:05:53",85]}


I then use a
forEach
loop to get all the data:

success: function(data) {
data.forEach(function(chartData) {
var series = window.chart1.series[0],
});
},


I want to use that ID in the json as a variable. So far I've tried:

var series = window.chart+chartData.id+.series[0]


but I get an error:

Uncaught TypeError: Cannot read property '0' of undefined


When I input the ID directly:

var series = window.chart1.series[0],


it runs without any issue and if I console.log(chartData.id) I get the correct ID
1
.

How do I use the nested ID in the json as a variable?

Answer

You can use property accessing [] syntax.It will evaluate the expression and return to the [] the value.

var series = window['chart' + chartData.id].series[0];