I have an object:

data = { badges: [ 0: { img:"/assets/img/badges/024-medal-31.png", title:"Rank 1" } ], email: "usermail@mail.com", id: "12345678", joinDate: timestamp, name: "User Name", } 

In the array of badges can be as many objects of the same structure. Why does the following code not do anything at all?

 $.each(data.badges, function() { console.log(this.img); }); 

each completely ignored, do not tell me why and how to get the information of each object in the badges ?

JSON.stringify (data):

{"badges": [], "email": "usermail@mail.com", "joinDate": "timestamp", "name": "User Name", "id": "12345678"}


The data created earlier approximately as follows:

 let userBadges = []; userInfo.badges.forEach(doc => { doc.badgeRef.get() .then(res => { userBadges.push( res.data() ) }) //data() = обьект {img: , title:} }); data.badges = userBadges; 

    1 answer 1

    It is not "ignored", but it does not reach it because of a syntax error. Unnecessary 0:

     var data = { badges: [ { img: "/assets/img/badges/024-medal-31.png", title: "Rank 1" } ], email: "usermail@mail.com", id: "12345678", joinDate: '', name: "User Name", } $.each(data.badges, function() { console.log(this.img); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    Update

    You are trying to output data without waiting for the completion of asynchronous functions, which is confirmed by the observed "badges":[] .

    • This is not the problem, the array was created earlier and looks like this. I took it from the console because it is decorated crookedly ... I will add information to the question if you say what to add. - Telion
    • @Telion Click the "Run Code" button. - Igor
    • I mean that I can not change the object itself, it is what it is because it was created automatically, and you changed the object in your question. I need to change the output of the object so that it would be displayed correctly with zero, I will add an approximate code for creating an object to the question. - Telion
    • Added, here is the code above creates exactly the structure that I showed. - Telion
    • @Telion Output console.log(JSON.stringify(data)); and copy to the question. - Igor