skip to Main Content

I have a nested array which looks like the example code below.

I need to access a nested array within my JSON array.

But the issue is that I always get undefined!

var json = {
    "status": "OK",
    "tickets": {
        "open_tickets": [{
            "id": "2",
            "assets": [{
                "id": 2446,
                "age": 4,
    
            }]
        }, {
            "id": "3",
            "assets": [{
                "id": 244564646,
                "age": 28,
            }]

        }]
    }
};

for(i=0;i<json.tickets.open_tickets.length;i++){

var id = json.tickets.open_tickets[i].id;
var age = json.tickets.open_tickets[i].assets.age;

$('.holder').append('<p>'+id+' '+age+'</p>')
 

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="holder">



</div>

The age variable is always undefined and I cant figure out why this is happening.

what am I doing wrong?

2

Answers


  1. try this out:

    for (var i = 0; i < json.tickets.open_tickets.length; i++) {
        var ticket = json.tickets.open_tickets[i];
        var id = ticket.id;
        var assets = ticket.assets;
        for (var j = 0; j < assets.length; j++) {
            var age = assets[j].age;
            $('.holder').append('<p>' + id + ' ' + age + '</p>');
        }
    }
    
    Login or Signup to reply.
  2. You can simplify this with a for Each loop to loop through json.tickets.open_tickets and access the assets array with [0].

    let holder = document.querySelector(".holder");
    var json = {
      "status": "OK",
      "tickets": {
        "open_tickets": [{
          "id": "2",
          "assets": [{
            "id": 2446,
            "age": 4,
    
          }]
        }, {
          "id": "3",
          "assets": [{
            "id": 244564646,
            "age": 28,
          }]
    
        }]
      }
    };
    
    json.tickets.open_tickets.forEach((e) => {
      holder.innerHTML += '<p>' + e.id + ' ' + e.assets[0].age + '</p>'
    });
    <div class="holder">
    
    
    
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search