Getting Cannot read property 'length' of undefined when parsing JSON array which has data in it in EJS template?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Getting Cannot read property 'length' of undefined when parsing JSON array which has data in it in EJS template?



Here is my code to render view and pass data.


var x = '{"products":[{"id":"1"},{"id":"2"},{"id":"3"}]}';
res.render('home', {test:x});



Here is my code to loop and show data


<ul>
<% for(var i=0; i<test.products.length; i++) { %>
<li>
<%= test.products[i].id %>
</li>
<% } %>
</ul>



I keep getting Cannot read property 'length' of undefined error. What exactly am I doing wrong here?




2 Answers
2



It seems like that view isn't getting test object, try to console.log it's value and see what it's showing. Moreover, You can loop through array of objects like this as well:


var products=test.products;
for (var key in products) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}



the object to which x refers is a string. you need to parse this as a JSON object using JSON.parse(x)


JSON.parse(x)






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Visual Studio Code: How to configure includePath for better IntelliSense results

Spring cloud config client Could not locate PropertySource

Makefile test if variable is not empty