0

how can i get the key name of the iterated item of a forEach loop?

const obj = {
  var1: 1,
  var2: 2,
  var3: 3,
}

obj.forEach((item) => {
  console.log(item.keyName) // o want to get var1, var2 and var3 on the console
})
Carlos Pisarello
  • 1,254
  • 5
  • 20
  • 39
  • 2
    That's not a valid object. Did you mean `obj = { var1: 1, var2: 2, var3: 3 }`? – Phil Oct 10 '19 at 23:03
  • 1
    `Object.keys(obj)` – marzelin Oct 10 '19 at 23:05
  • 1
    Make sure to read more than just the accepted answer in the linked duplicate – Phil Oct 10 '19 at 23:06
  • Great!, @connexo you can put your comment as answe so i can choose it as best answer – Carlos Pisarello Oct 10 '19 at 23:14
  • 2
    Just upvote https://stackoverflow.com/a/39463695/3744304 and/or https://stackoverflow.com/a/46625288/3744304. Also I made I mistake, it's got to be `Object.entries(obj).forEach(([key, value]) => console.log(key, value));`. You need to destructure the argument, or access it using `Object.entries(obj).forEach((entry) => console.log(entry[0], entry[1]));` – connexo Oct 10 '19 at 23:18

0 Answers0