0

I am using for of loop of JavaScript. My code is like below.

for (let [key, value] of data) {
   if(key == 0) {
     // do something.
   } else {
   // do something.
  }

I am getting below error.

Uncaught (in promise) TypeError: data[Symbol.iterator]().next().value is not iterable

How to use Key in for of loop of JavaScript ?

abu abu
  • 6,599
  • 19
  • 74
  • 131

2 Answers2

3

If your data is an object you could do

const data = {
a: 1,
b: 2,
c : 3
}

for(let [key, value] of Object.entries(data)){
 console.log(`key: ${key} and value: ${value}`)
}

As @Maik Lowrey noted the problem seems to be a different

Looks like data is a promise (or an array of promises)

int the first case you just have to call .then

const data = Promise.resolve({
    a: 1,
    b: 2,
    c: 3
  })


data.then(d => {
  for (let [key, value] of Object.entries(d)) {
    console.log(`key: ${key} and value: ${value}`)
  }
})

const data2 = [4, 5, 6].map(n => Promise.resolve(n))


Promise.all(data2).then(d => {
  for (let [key, value] of Object.entries(d)) {
    console.log(`key: ${key} and value: ${value}`)
  }
})
R4ncid
  • 6,944
  • 1
  • 4
  • 18
1

Your data is still a Promise at the time of the loop. Apparently you are getting data from an API or something similar. This means you have to wait until the Promise is resolved. You can work with async await or loop inside then().

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79