Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to loop thru my nested array of json objetcs..

Here's the loop:

        $("#test").text("");
        for(var i=0;i<obj.length;i++){
            $("#test").append(obj[i].line_item + ", ");
            for(var j=0;j<obj[i].length;j++){
                $("#test").append(obj[i][j].iid + ", ");
                $("#test").append(obj[i][j].name + ", ");
                $("#test").append(obj[i][j].price + ", ");
                $("#test").append(obj[i][j].lid + ", ");
                $("#test").append(obj[i][j].picture + "<br />");
            }//for for
        }//for

console.log i showing no errors, when i echo the php-script I get this output:

[{"line_item":"base","0":
{"iid":"1","name":"mix","price":"30","lid":"1","picture":"images\/mix.jpg"},
"1":{"iid":"2","name":"green","price":"30","lid":"1","picture":"images\/green.jpg"}}]

The problem: When I loop thru the arrays i only get the output: base, in my html file.

My question: How can i get hold of the inner array objects?

share|improve this question

2 Answers 2

up vote 0 down vote accepted

I'm guessing you're trying to do this :

var a = [];

$.each(obj, function(i, arr) {
    a.push(arr.line_item);
    $.each(arr, function(j, ob) {
        if (typeof ob == 'object') {
            $.each(ob, function(key,value) {
                a.push(value)
            });
        }
    });
});

$("#test").text(a.join(', '));

FIDDLE

share|improve this answer
    
This did the trick!! Thx a lot! Been wondering quit some time now! –  Conjak Jul 28 '13 at 17:43

That's because you are using an object an not an array, so you can't do:

 obj[i].length

An easy easy way to solve that is to put the items inside an array, sample JSON:

[{"line_item":"base", "items": [
{"iid":"1","name":"mix","price":"30","lid":"1","picture":"images\/mix.jpg"},
{"iid":"2","name":"green","price":"30","lid":"1","picture":"images\/green.jpg"}]}]

And change your code to:

$("#test").text("");
for(var i=0;i<obj.length;i++){
  $("#test").append(obj[i].line_item + ", ");
  for(var j=0;j<obj[i]['items'].length;j++){
    var item = obj[i]['items'][j];
    $("#test").append(item.iid + ", ");
    $("#test").append(item.name + ", ");
    $("#test").append(item.price + ", ");
    $("#test").append(item.lid + ", ");
    $("#test").append(item.picture + "<br />");
  }//for for
}//for
share|improve this answer
    
will look into this as well! Thx! –  Conjak Jul 28 '13 at 17:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.