0

Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?

I am JavaScript beginner and have created the following array of objects in Javascript:

var values = [[{
       x_value: {
           x_axis: 1,
           y_axis: 1.8445
       },
       y_value: {
           x_axis: 1,
           y_axis: 1.2445
       },
       z_value: {
           x_axis: 1,
           y_axis: 1.1445
       }
   }],[{
       x_value: {
           x_axis: 2,
           y_axis: 1.35
       },
       y_value: {
           x_axis: 2,
           y_axis: 1.245
       },
       z_value: {
           x_axis: 22,
           y_axis: 1.345
       }
   }],[{
       x_value: {
           x_axis: 3,
           y_axis: 1.087
       },
       y_value: {
           x_axis: 3,
           y_axis: 1.125
       },
       z_value: {
           x_axis: 3,
           y_axis: 1.95
       }
   }]];

I would like to access the value of the x_axis of, say, y_value in values[0], what methods should I use? Thanks in advance

Community
  • 1
  • 1
Anto
  • 4,265
  • 14
  • 63
  • 113
  • I would recommend to read the [MDN Javascript Guide](https://developer.mozilla.org/en-US/docs/JavaScript/Guide) to learn the basics, and/or http://eloquentjavascript.net/. – Felix Kling Jan 25 '13 at 12:23

2 Answers2

2

Since you placed your objects in another array (holdings the objects only), then you need to make something like that to get the values:

var x_axis = values[0][0].y_value.x_axis,
    y_axis = values[0][0].y_value.y_axis;
VisioN
  • 143,310
  • 32
  • 282
  • 281
1

If at all possible, there's no good reason to wrap each object in another array, like you're doing:

 var yourCode = [[{}],[{}]];
 var better = [{},{}];

If you can change the data, just make sure that your script receives a single array, containing all objects (like the var better format above).
As things now stand, you'll have to access the first index of the inner array, too:

var x = values[0][0].x_axis;
var y = values[0][0].y_axis;

If you change the format to fit what I sugested:

var x = values[0].x_axis;

Note that objects also support the square-bracket notation, which is very useful if the property-name/key is the value of a variable:

var getProp = 'x_axis';
console.log(values[0][0].getProp);//undefined, looks for property called getProp
console.log(values[0][0][getProp]);//returns value of x_axis property, variables value is used

Is enough... If you can, please use the second format, really. Not only does it require less typing, but however minor the overhead is, an array is not free. You're creating a second object (instanceof Array) that is completely irrelevant.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149