JSON array of zero length even with elements?
I receive a JSON response from the server and create a Javascript object. The structure is as follows:
var response = {
key1:[],
key2:[],
key3:[],
key4:[],
key5:[]
}
When the request completes, the object response
completed successfully as follows:
Object (*expandable):
key1: Array[0]
key2: Array[0]
key3: Array[0]
key4: Array[20]
key5: Array[113]
Now I want to store the information in the database. I created a function and I have console.log
an answer object to make sure this is ok (this is where it gets interesting - see comments):
function setupDatabase(){
console.log(response); // prints the response correctly (see response above)
console.log(response.key5); //prints key5: Array[0]. If I expand the Array[0] all the elements are inside.
console.log("key5: "+response.key5.length);//prints 0!!
}
It's okay if the first 3 keys are 0 because there are no items for them. The other 2 are fine. Why am I taking this log when I run 3 commands console.log
on the same object in a row? Did I miss something?
source to share
This is a problem with the way it console.log
works in some browsers. Instead, you can use console.log(JSON.stringify(response.key5))
to get a "just in time" view.
Basically, it console.log
registers the top level of something, but if you expand one of these later , it will show you the contents as they were when you expanded it , not when you launched it. So response.key5
was empty when you registered it, but then added things to it before expanding it in the console.
It's pretty hopeless. For example, in Chrome it might ask if the console will open or close when it happens console.log
. If you close the console, it registers a static thing that you cannot extend.
Here's a simple example to demonstrate the problem.
In Chrome:
- Make sure the console is closed.
- Run this snippet.
- Open your console.
You will see an array, and if you deploy, you will see an entry that was added after the line console.log
.
Contrast with console.log(JSON.stringify(...))
:
console.dir
does something similar to console.log
, but always writes the "live" version, even if the console is closed:
When you close the console, then open it later, it console.dir
shows Array[1]
with an extension arrow which then shows you the entry. But bizarrely, if you have your console open, you see Array[0]
- but then its extension shows you an entry:
This type makes sense because the array was empty when you registered it, but then you see its contents from the moment you expanded it.
source to share