0

I have the following json response from server:

  $data=[[

    {"left":{"p1":{"x":0,"y":0},"p2":{"x":0,"y":15}},
     "right":{"p1":{"x":15,"y":0},"p2":{"x":15,"y":15}},
     "up":{"p1":{"x":0,"y":0},"p2":{"x":15,"y":0}},
     "bottom":{"p1":{"x":0,"y":15},"p2":{"x":15,"y":15}}},

    {"left":{"p1":{"x":0,"y":15},"p2":{"x":0,"y":30}},
     "right":{"p1":{"x":15,"y":15},"p2":{"x":15,"y":30}},
     "up":{"p1":{"x":0,"y":15},"p2":{"x":15,"y":15}},
     "bottom":{"p1":{"x":0,"y":30},"p2":{"x":15,"y":30}}}

    ],
[

{"left":{"p1":{"x":0,"y":0},"p2":{"x":0,"y":15}},
 "right":{"p1":{"x":15,"y":0},"p2":{"x":15,"y":15}},
 "up":{"p1":{"x":0,"y":0},"p2":{"x":15,"y":0}},
 "bottom":{"p1":{"x":0,"y":15},"p2":{"x":15,"y":15}}},

{"left":{"p1":{"x":0,"y":15},"p2":{"x":0,"y":30}},
 "right":{"p1":{"x":15,"y":15},"p2":{"x":15,"y":30}},
 "up":{"p1":{"x":0,"y":15},"p2":{"x":15,"y":15}},
 "bottom":{"p1":{"x":0,"y":30},"p2":{"x":15,"y":30}}}

]
]

I would like to alert every x of p1 point in left.

$.getJSON("jetData",
          function(data) {
      $.each(data, function(i,item){
          alert(data[i].left.p1.x);

        }); 
      });

I'm getting

Uncaught TypeError: Cannot read property 'p1' of undefined 

How to do it correct?

Update:

I'm sorry I posted wrong example it just took me some time to realize that we are talking about 2x2 matrix. so I need to print value in 2 loops.

4

2 回答 2

1

Well, your data is double-enclosed in the array structure. That would require you to use data[0][i].left.p1.x to iterate through it (or something smarter -- hard to tell without more information about what is being serialized and how).

于 2012-07-04T22:45:01.573 回答
1

For your updated question, you'll need a nested loop to loop both the outer and inner loops.

$.getJSON("jetData", function(data) {
   $.each(data, function(i,item) {
       $.each(item, function(j, inner_item) {
           alert(inner_item.left.p1.x);
        // alert(data[i][j].left.p1.x);  // same thing
       });
   }); 
});

You have 2 outer Arrays.

change this...

$.each(data, function(i,item){

to this...

$.each(data[0], function(i,item){

...so that $.each is iterating the array that directly contains the objects.


Not directly related, but this...

alert(data[i].left.p1.x);

can be written as this...

alert(item.left.p1.x);

Same thing, but a little shorter.

于 2012-07-04T22:45:10.750 回答