-1

I'm struggling with a big JSON Object and I got into a weird problem:
My Object has the following structure:

const bar = {
  arr: []
}

If I try to set its value in this way bar.arr.foo = 'ciao' it doesn't give me any error. The result object is this

enter image description here

What is that strange "Array(0)" that the Chrome dev tools are pointing out? If I try to type typeof bar.arr it says "object"

But doing JSON.stringify(bar, null, 2) results in '{\n "arr": []\n}'

Ale TheFe
  • 1,124
  • 12
  • 30
  • 2
    https://stackoverflow.com/questions/9952126/add-a-property-to-a-javascript-array – Roberto Zvjerković May 27 '22 at 12:50
  • 2
    It’s not clear what you think the issue is. You can set properties on (basically) anything, including an array. `typeof anArray` will return `object`; that’s just how JS is (and why there’s `Array.isArray`. As far as “what happens”, exactly what’s shown. – Dave Newton May 27 '22 at 12:50
  • 2
    You have an empty array with 0 elements (`Array(0)`). You set an additional property on it. That works like it does on any object. It's still an array. If you stringify it, the rules of stringifying an array apply, which will create just `[]` because there is no array literal notation that would include extra properties. – CherryDT May 27 '22 at 12:51
  • @Roberto Zvjerković thanks, that answer gave me the explanation I needed – Ale TheFe May 27 '22 at 12:55

0 Answers0