0

I'm very confused in Javascript for getting JSON value using the defined variables.

Here is JSON data below:

 AllData =  {data0 : {name: "John", age: 31, city: "New York"}}, 
{data1 : {name: "Marin", age: 20, city: "New York"}},
{data2 : {name: "Marin", age: 20, city: "New York"}}

Of course I can get the value using "AllData.data0", however, I want to get all the data in for loop.

for (i=0;i<AllData.length;i++) { 
      num = i.toString()
      data = "data" +i
      AllData.data
}

But it always return "undefined", intial language that I've been using is Python so that I'm very confused in javascrtip, could you help on this matter?

Thanks in advance.

Hyo
  • 23
  • 3
  • That's [JavaScript, not JSON](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Quentin Jun 04 '21 at 12:35
  • 1
    First, **declare your variables** with `let` or `var` or `const`. Now, `AllData` does not have a `.length` property, because it is not an array. – Pointy Jun 04 '21 at 12:36
  • The duplicate shows how to do what you're ultimately trying to do, access a property dynamically using the name of that property as a string. Though the code shown appears to have other issues as well, for example it's not clear what exactly you expect `AllData` to actually be. It looks like it would just be that first object and the other two objects would be ignored. Perhaps you meant to make it an array? If that's the case, wrap those three objects in `[]`. But then your loop is trying to treat `AllData` like *both* an array *and* an object... – David Jun 04 '21 at 12:38
  • Thanks for the comment, please ignore the data that I shared..., all data correctly replied from server with multiple JSON type like below: data0: {ServiceNo: "129", Operator: "SBST", NextBus: {…}, NextBus2: {…}, NextBus3: {…}} data1: {ServiceNo: "130", Operator: "SBST", NextBus: {…}, NextBus2: {…}, NextBus3: {…}} data2: {ServiceNo: "139", Operator: "SBST", NextBus: {…}, NextBus2: {…}, NextBus3: {…}} data3: {ServiceNo: "139M", Operator: "SBST", NextBus: {…}, NextBus2: {…}, NextBus3: {…}} , but I'd like to know to how to get the values using dynmic veriable.. – Hyo Jun 04 '21 at 12:47
  • I've tried it using defined var, but it's not working .. and console output is showing correct name of variable.. but it's still returning undefined `for (num=0; num < Object.keys(BusArrivalResponse).length; num++) { number = num.toString() var data = "data"+number var data = data.toString() console.log(data) console.log(BusArrivalResponse.data) }` – Hyo Jun 04 '21 at 12:50
  • Oh it's working with AllData[data] Thanks ~!! guys~! – Hyo Jun 04 '21 at 12:53

0 Answers0