skip to Main Content

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.

2

Answers


  1. 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) }
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search