0

Hi am newbie to JSON i dont know how to iterate JSON over $.each function i worked on it but it display always shows value as undefined am not sure why it is

here how my json looks saved it as new file data.json

{ "users":[
            {
                "firstName":"Ray",
                "lastName":"Villalobos",
                "joined": {
                    "month":"January",
                    "day":12,
                    "year":2012
                }
            },
            {
                "firstName":"John",
                "lastName":"Jones",
                "joined": {
                    "month":"April",
                    "day":28,
                    "year":2010
                }
            }
    ]}

here i need to iterate name with Joined date in JSon and i iterate it over Jquery by like this

$(function(){
    $(document).on('click', '.users', function(e){
        e.preventDefault();                                            
        $.getJSON( "js/data.json", function( data ) {
          var items = [];
          $.each( data.users, function( key, val ) {
            console.log(data.users);                           
            items.push( "<li id='" + data.users.firstName + "'><span><p>" + data.users.firstName + "</p></span></li>" );
          });
          $( "<ul/>", {
            "class": "users-lists",
            html: items.join( "" )
              }).appendTo( ".nlst" );
       });
    });
});

help me out

1 Answer 1

1

In your jquery code change this line

items.push( "<li id='" + data.users.firstName + "'><span><p>" + data.users.firstName + "</p></span></li>" );

to

items.push( "<li id='" + val.firstName + "'><span><p>" + val.firstName + "</p></span></li>" );

jquery doc Here

Sign up to request clarification or add additional context in comments.

2 Comments

thanks i got and a small doubt how do i iterate the nested object within the users named as joined?
you need to add another $.each loop inside $.each loop. pass the value as parameter for inside $.each loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.