Hi i have a simple question, i want to count how many results i receive when getting result from API. Im using OMDb API so result looks like this:
[{ Title: 'Hangover',
Year: '2014',
imdbID: 'tt3653728',
Type: 'movie',
Poster:
'https://m.media-amazon.com/images/M/MV5BN2MzM2Y4NWYtYmUzNS00YWQ3LTkyYTUtOTdkY2I4YzVlMGM4XkEyXkFqcGdeQXVyMjkxNzQ1NDI@._V1_SX300.jpg' },
{ Title: 'Our Colonial Hangover',
Year: '2014',
imdbID: 'tt4132226',
Type: 'movie',
Poster: 'N/A' } ]
I just want to know is how many object literals are in the array. I've tryed to use Object.keys(data).length but it seems I'm not receiving right information. Here is express:
app.post("/search", (req, res) => {
let search = req.body.userSrc;
Recent.findOne({
Title: search
}, (err, foundData) => {
if (err || foundData == null) {
fetch("http://www.omdbapi.com/?s=" + search + "&apikey=b322e698")
.then(response => response.json())
.then(data => {
console.log("API RESPONSE");
console.log(data.Search);
res.render("index", {
result: data.Search
});
});
} else {
console.log("Found Local");
res.render("index", {
result: foundData
});
}
});
});
Here is my EJS:
<div class="col-md-12 pt-3 ">
<div class="row justify-content-center">
<% if(typeof(result) !== "undefined" ) {%>
<% if(Object.keys(result).length >1 ){ %>
<% result.forEach(result => { %>
<div class="col-xs-12 col-md-6 col-lg-3 p-2 m-2">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="<%=result.Poster%>" alt="Card image cap">
<div class="card-body">
<p class="card-text"><%=result.Title%></p>
<a href="/search/<%=result.imdbID%>" class="btn btn-primary">More</a>
</div>
</div>
</div>
<%})}else{ %>
<div class="col-xs-12 col-md-6 col-lg-3 p-2 m-2">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="<%=result.Poster%>" alt="Card image cap">
<div class="card-body">
<p class="card-text"><%=result.Title%></p>
<a href="/search/<%=result._id%>" class="btn btn-primary">More</a>
</div>
</div>
</div>
<%}}%>
</div>
What i need to do is if the movie is find locally in database that means that there will be only one object literal in array and if there is no local data it will search it trough Movie APi and give me more than 1 result. EJS gives me error if i have 1 result(local in database) and run in in forEach method. If i know there is just one result i can use and if statment and not run it trough forEach.
Im sorry but i dont know how to explain this.