Home > Mobile >  ReferenceError when trying to destructure Object.entries() in for-loop
ReferenceError when trying to destructure Object.entries() in for-loop

Time:01-03

I figured out how to make this work, but I cannot for the life of me understand how this can happen!

This throws [ReferenceError: Property ‘date’ doesn’t exist]:

for (const [date, items] of Object.entries(object)) { console.log(date) }

This works:

for (const entries of Object.entries(object)) {
      const date = entries[0]
      const items = entries[1]
      console.log(date)
 }

It's the same object, every single time. It only has one entry, This is how it looks when I log it using Object.entries(object):

[
   "2022-01-02",
   {
      "a":[objects],
      "b": object,
      "c":[objects]
   }
]

If I log date in the working code block, I can see date being logged. But trying to log date when restructured, it throws. So seems like it's throwing because I'm trying to destructure the array. But WHY!? I'm currently on React Native, if that is valuable in any way.

CodePudding user response:

I think it's because you're redeclaring the variable items.

Try changing the destructured variable name to something else:

const items = {
  '2023-01-02': [
    "value 1"
  ]
}

// works fine
for (const [date, entryItems] of Object.entries(items)) { console.log(date) }

// throws
for (const [date, items] of Object.entries(items)) { console.log(date) }

CodePudding user response:

This is because your object is an array at base, then you cannot destructurate an array with keys, but with indexes

let data = [
   "date",
   {
      "a":[objects],
      "b": object,
      "c":[objects]
   }
]

Data doesnt have keys but indexes... There is no entry with key date or items

  • Related