Here is the code:
let test = [];
test.someProp = "haha";
console.log(test); // result: [ someProp: 'haha' ]
console.log(JSON.stringify(test)); // result: []
console.log(test.someProp); // result: haha
console.log(JSON.stringify(test)); // result: []
How console.log(test)
returns an object and the line after it console.log(JSON.stringify(test))
returns an empty array ?
3
Answers
The reason you can see someProp: ‘haha’ is because the console interprets the object differently on different dev tools. On the SO snippet tool, as you can see, the result is []. Here is why:
Arrays in JS are objects with numeric keys. Because they are objects, they can have properties like your someProp. This doesn’t add an element to the array (which would require a numeric index). That is why you might see [someProp: ‘haha’]. Some consoles use the names of the props and values to print the object to help devs with debugging. When you log test.someProp, it accesses only the property you asked for as a value.
When you JSON.stringify, it converts only the array elements into the JSON string because you called it on the array. That is why you once more see [].
In brief, this quote from MDN should shed some light on this:
The
Array
is still anArray
. It is also, and always was, anObject
too. How a given type ofObject
is converted to JSON will usually depend on thetoJSON()
method of its prototype, though in the case ofArray
(being a built in type) it is treated as a special case and has a default implementation which doesn’t, for example, output thelength
property ofArray
in the stringified output but rather the[...]
format you see.As @jonrsharpe pointed out, JSON can’t represent an array with extra properties.
However, if you need to translate such an array into JSON and back, you can do it like this: