0

When i see my book object in console it shows array but when i try to iterate it does not iterartes in loop.

console.log(book);// logs array of length 6
console.log(typeof book);// logs -> object
console.log(book.length);// logs 0

//this for loop does not iterates.

for(let i of book)
        {

           //logic
        }

Please help me how to iterate? my book object looks like below on console.

my book object looks like below on console.

  • 2
    Were missing some details here, how are you getting book, could you show more of the process.? Using a hunch, I've a feeling it's an async issue.. – Keith May 11 '18 at 09:33
  • i am passing it in function. this above code is of the function. – Abhay Kumar May 11 '18 at 09:34
  • Actualyy i am writing an agular 2 pipe in which i ma getting this book object. – Abhay Kumar May 11 '18 at 09:35
  • 1
    That's not really helping, could you show the code were you getting `book`, if this is an Ajax request, chances are your running into an `async` issue. – Keith May 11 '18 at 09:36
  • How is `book.length` zero? Did you not just say that the array has 6 elements in it? – bugs May 11 '18 at 09:36
  • Did you try with `for(let i in book)`. https://stackoverflow.com/questions/29285897/what-is-the-difference-between-for-in-and-for-of-in-javascript – Gardelin May 11 '18 at 09:40
  • Is it throwing any error? – Harsh Jaswal May 11 '18 at 09:44
  • 2
    @tuna In modern JS, best stay away from `in` unless you want to mess about with `hasOwnProperty`. `of` works with any itterable in a consistent way. – Keith May 11 '18 at 09:44
  • @AbhayKumar, If you feed Angular pipe with Async data, initially it returns nothing on page load as there's no data. So your book array could be empty. Once it gets the data, It processes. – Amaresh C. May 11 '18 at 09:47
  • Why do you expect the loop to iterate over an *empty* array?! Logically it iterates zero times over an array with zero elements. – Jonas Wilms May 11 '18 at 10:00
  • Hi All, Thanks for your help issue stands resolved :) – Abhay Kumar May 12 '18 at 08:09
  • I was creating a custom pipe for ngFor and was passing async object i made my PIPE impure and it started getting the array properly. – Abhay Kumar May 12 '18 at 08:10

1 Answers1

-3

let i of book is wrong. Since it is an array of object, try to do below.

  book.forEach( function (bookItem)
{
    Your logic
});