node.jsjsonejsviewengine

Cannot read property 'firstname' of undefined in view engine node js


I am trying to display json data on a website using view engine (ejs) but I am facing following error Cannot read property 'firstname' of undefined this is my program

node.js

io.readEmp().then(function(data){
    res.render('Dashboard',{data:data});
}).catch(function(err){console.log(err.message);});

index.ejs

<ul class="list-group list-group-flush">
    <% for(var key in data){%>
        <li class="list-group-item"><%= data.key.firstname %></li><%}%>
</ul>

jsonfile

{
    "id01":{"firstname":"abc","lastname":"xy"},
    "id02":{"firstname":"pqr","lastname":"xy"}
}

error

Cannot read property 'firstname' of undefined

Solution

  • If you have data as an object like you display then 'key' will be the item key and you need to use the key access notation for an object thusly:

    <ul class="list-group list-group-flush">
        <% for(var key in data){%>
            <li class="list-group-item"><%= data[key].firstname %></li><%}%>
    </ul>
    

    'key' for the first item will be "id01", so this is equivalent (on the first pass) for saying data.id01.firstname.