How to access children

Children

As mentioned in the introduction, each cJobject is either a key/value pair or is the parent of some more cJobjects. Accessing the children of a cJobject is straightforward, and as close to the JavaScript as possible within the confines and rules of the VBA language syntax.


By key , for example 



		



or by childIndex



		


This is roughly equivalent to job.somekey or job[0] in JavaScript except that cjobject has a childIndex for both array members and regular objects (JavaScript only has indices for Arrays), and the cJobject index starts at 1 (JavaScript starts at 0)

Grandchildren

You can access grandchildren and so on in a couple of ways too



		


is equivalent to



		


which is close to the JavaScript



		


You can also mix index and named keys, so 



		


is equivalent to



		


  and the JavaScript equivalent 



		


Arrays

As mentioned arrays are not really much different to regular objects, except that their key is the same value as their childIndex. 


Using the test data from cJobject deep dive here’s an example of extracting and stringifying the the first array member 



		


We can print the value of the name property of the first array member



		


Which is equivalent to this



		


Note that we can always stringify (convert to JSON) any cJobject – even a single property



		


How many children

You can test if a cJobect has children like this



		


The number of children is



		


job.hasChildren is equivalent to job.children.count > 0. In JavaScript you could only do this test ( if (job.length > 0) )  on an Array. For an object you would need to say …  if (Object.keys(job).length > 0)

Testing if a child exists

Accessing a child that doesn’t exist will return Nothing, so you can simply test any of the syntax already mentioned for Nothing.



		


for convenience, I provide an isSomething()  function also, so the above is equivalent to



		


This is roughly equivalent to the JavaScript 



		


except that JavaScript will throw an error if job is not an Array,  or element 1 does not exist, only making a successful test on the final property – age. cJobject will not fail, but return Nothing.

Now let’s look at some more cJobject topics.

For more on this see How to use cJobject