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 ?

2
  • 7
    The problem is not with your loop, it's with the value of data. Where does it come from? Commented Apr 26, 2022 at 12:22
  • 2
    I vote for reopen because the problem is not the loop. It is a promise problem. Commented Apr 26, 2022 at 12:33

2 Answers 2

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}`)
  }
})

Sign up to request clarification or add additional context in comments.

Comments

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().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.