Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of Array in Object doesn't match

I'm trying to use the tree hierarchy in D3 and got stuck. I thought I'm building the JSON correctly but when I looked at the object in Developer's Tool, I see the following:

chrome

Notice the first line shows the dependents array has 0 length but when expanded, you can clearly see dependents has 3 objects. When I stringify it, I get the following:

{"attributes":{"id":0,"name":"root"},"dependents":[]} 

Any idea what could be wrong? Thanks!

like image 285
PLui Avatar asked Mar 08 '13 15:03

PLui


People also ask

How do you find the length of an array of objects?

You can simply use the Object. keys() method along with the length property to get the length of a JavaScript object. The Object. keys() method returns an array of a given object's own enumerable property names, and the length property returns the number of elements in that array.

Does Size () work on arrays?

Unlike the String and ArrayList, Java arrays do not have a size() or length() method, only a length property.

Do arrays have length property?

The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

Does splice change array length?

splice doesn't change the length of the array.


1 Answers

This problem usually happens when you change the object after having logged it because Chrome doesn't deep-copy the object when you log it but simply stores a reference.

The tree isn't immediately built but only when needed and sometimes it's based on a more recent value.

If your object is light enough, you can clone it yourself if you really want to see the value at logging time :

console.log(JSON.parse(JSON.stringify(myobject)));

If your object is big or recursive, you may find it a little more difficult to clone it. Personally I have my own tool, JSON.prune.log.

As ignoring the browser's optimization comes with a cost, you should most often simply take into account this behavior and log only primitive if you want to be sure of their logging time value...

like image 129
Denys Séguret Avatar answered Oct 13 '22 03:10

Denys Séguret