0

Here is the JSON example:

jsonData:

{ "Device": { "Content": { "UL": { "index0": "12", "index1": "1", .... "index31": "5", } } } }

This is what I tried, but it didn't work:

var index = [];
var jsonDoc = JSON.parse(data);
for(var i =0; i<32 ; i++)
{
  var $arr = "index"+i;
  index.push( jsonDoc.Device.Content.UL.$arr);
}

How can I extract the index from 1 to 31 and put it in the index array?

austinc
  • 285
  • 2
  • 5
  • 15

3 Answers3

1

You can access hashes with the [] operator as well:

index.push( jsonDoc.Device.Content.UL[$arr]);
Gavriel
  • 18,880
  • 12
  • 68
  • 105
  • @mplungjan, it has an explanation and a solution with working code. What do you miss? – Gavriel Feb 01 '16 at 06:35
  • Huge duplicate and already answered in my comment - I know you did not see it but should be closed – mplungjan Feb 01 '16 at 06:37
  • @Gavriel this the only way to access values when you have key reference in a var. `key[var]`. – Jai Feb 01 '16 at 06:37
  • @Jai, right, the "as well" I meant that jsonDoc["Device"]["Content"]["UL"][$arr] would work as well for example. In places where you have variables, you don't have another choice – Gavriel Feb 01 '16 at 06:51
1

try converting JSON to array .

var o = jsonDoc.Device.Content.UL;
var arr = Object.keys(o).map(function(k) { return o[k] });

refer: Converting JSON Object into Javascript array

Community
  • 1
  • 1
Vegeta
  • 1,319
  • 7
  • 17
1

You can use for statement to iterate through an object's values:

var index = [];
for(var name in jsonDoc.Device.Content.UL) 
{ 
    index.push(jsonDoc.Device.Content.UL[name])); 
}
Michael
  • 1,453
  • 3
  • 20
  • 28