1

I am trying to access to an object attribute with an autogenerated key, which means I have to iterate through its keys and access the parent object with the index. The problem comes when I console log the index is correctly fetched, but when I access the object attribute it returns an empty object (not undefined).

      console.log(detailArray)
      detailArray.forEach((detail) => {
        for(var i in detail) {
          if (detail.hasOwnProperty(i)) {
              console.log(i, detail[i])
          }
        }
      })

These are the values returned in the first console log

[
  {
    "2gC28U711o": {
      "number": "654324232",
      "operator": {
        "id": 0
      },
      "paymentModality": "contract",
      "action": "portability"
    }
  }
]

and these are the loop console log:

 2gC28U711o  {}

What am I missing here?

UPDATE This code is inside a function called in each success of several async calls, with a counter to verify that we enter here when all the calls have ended. Outside this function the loop works fine, but inside it doesn't

Thanks in advance.

var detailArray = [
  {
    "2gC28U711o": {
      "number": "654324232",
      "operator": {
        "id": 0
      },
      "paymentModality": "contract",
      "action": "portability"
    }
  }
]

      detailArray.forEach((detail) => {
        for(var i in detail) {
          if (detail.hasOwnProperty(i)) {
              console.log(i, detail[i])
          }
        }
      })

1 Answers1

0

After some investigation, I found the error. Everthing comes from console.log not being that reliable when it comes to know the exact value of something in a loop. I made a JSON.stringify(detailArray) and it appeared empty as in the loop console.log, which means console.log was printing data not yet filled.

After some rearrangement the code now works fine.

This link was pretty usefull to find out what could be.