1

How would you reference a value in a Javascript object without the key?

So, given the object:

var JSONdata= [ 
    {"index":"1","var1":1,"var2":2}, 
    {"index":"2","var1":3,"var2":2}, 
    {"index":"3","var1":3,"var2":1}, 
    {"index":"4","var1":2,"var2":1}, 
    {"index":"5","var1":1,"var2":3}, 
]; 

Say I want to reference the values of var1 and var2 in a loop, but the names "var1" and "var2" change and the number of variables also changes.

So in Pseudocode:

while ( i < JSONdata.length ) {
   for (j = 1 to Num_variables) {
       Give me the value for varN
   next j
   }
i++
}

Thanks

2
  • Do you want to exclude the index property but include all other properties of each object? Commented Apr 14, 2011 at 22:18
  • You're right in your assumption Russ. I am using the data to construct a plot and the index variable is my x-axis, then I want to loop through every other variable. The answers below are right on. Commented Apr 15, 2011 at 13:03

2 Answers 2

1
var JSONdata= [ 
  {"index":"1","var1":1,"var2":2}, 
  {"index":"2","var1":3,"var2":2}, 
  {"index":"3","var1":3,"var2":1}, 
  {"index":"4","var1":2,"var2":1}, 
  {"index":"5","var1":1,"var2":3}
]; 

var fields=[
  "var1",
  "var2"
];

for(var i=0, ii=JSONdata.length; i<ii; i++){
  for(var j=0, jj=fields.length; j<jj; j++){
    $('#hello').html($('#hello').html()+' '+JSONdata[i][fields[j]]);
  }
  $('#hello').html($('#hello').html()+' '+'<br/>');
}

see there http://jsbin.com/ufege4/edit

1
  • Perfect answer Avrelian. This allows for any variables names rather than just var1 var2 etc. Thanks and I really like that jsbin.com preview tool. Commented Apr 15, 2011 at 13:08
1

The obj.propertyName notation in JavaScript is syntactic sugar for obj['propertyName'] -- So, you can access your vars using: JSONData[i]['var'+j];

1
  • Thanks Jason. I had tried JSONdata[i][j] with no success but did not realize I could use a numerical value for the first array object dimension and a string value for the second dimension. Commented Apr 15, 2011 at 13:06

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.