Search code examples
javascriptjqueryjsonapitrello

How do I traverse nested arrays/objects in JSON data?


I'm trying to display multiple checklists from individual cards in Trello. I can get access to the checklist as multiple, nested objects but I don't know how to traverse deeper to pull out the actual text and make it list items.

 Trello.get("cards/" + cardID + "/checklists", function(checklists) {
   console.log(checklists);
 });

the console log

data: http://jsbin.com/OzEdUkU/2/edit

How do I traverse all the way down to the name of the checkItem array objects?


Solution

  • This takes care of everything in your data set. Live demo here (click).

    $.each(checkList, function(i, obj) {
      console.log(obj);
      $.each(obj.checkItems, function(j, checkItem) {
        console.log(checkItem);
      });
    });
    

    checkList is an array (set) of objects. In your sample data, there are two objects nested in checkList, so the first $.each is for each object.

    Each object has some properties with string values and the property checkList itself is an array, so the second $.each is looping through that object's checkItems array. checkItems only contains properties with string values, so there is no additional nesting.

    Also note that $.each is just a jQuery shorthand function for traditional for loops and could be replaced with a normal for loop or the newer built-in js function forEach.