0

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?

kevinabraham
  • 1,378
  • 4
  • 28
  • 55
  • You're probably using `window.chart1` variable before the value is assigned to it. See [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Tushar Aug 23 '16 at 07:25

1 Answers1

1

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];
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112