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:
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!
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.
Unlike the String and ArrayList, Java arrays do not have a size() or length() method, only a 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.
splice doesn't change the length of the array.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With