-1

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.

  • 7
    [`array.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)? – Alexander Nied Aug 27 '20 at 14:58
  • 2
    You're getting an array and array by default has `length` property. – Varit J Patel Aug 27 '20 at 14:58
  • Please provide the code that causes `Object.keys(data)` not to work. I suspect that you are dealing with [asynchronous calls](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – Ivar Aug 27 '20 at 15:02
  • `Object.keys(data).length` on array given you the array elements length. Try `Object.keys(data[0]).length * data.length` if your object has same number of keys – Prathap Reddy Aug 27 '20 at 15:04
  • @AlexanderNied Easiest solution is the best solution. Thanks! – Denis Stojković Stole Aug 27 '20 at 15:45

2 Answers2

0

array.length will give you the length of items inside the array returned. just replace array with whatever variable name it's actually stored in. length works for arrays, and not objects... if you want to get a count of nested objects, that's a bit trickier.

altruios
  • 986
  • 1
  • 10
  • 29
0

It is not clear entirely what you want. If you want the number of objects in the returned array, it is as simple as getting the length of the array itself.

let count = data.length;

If you want the number of object literals for an object in the array:

let count = Object.keys(data[0]).length;

(where data is the array returned from the API).

lanxion
  • 1,350
  • 1
  • 7
  • 20