July 13, 2021, 6:14pm
Hi all, does anyyone know how I can return the amount of child nodes in a JSON node.
For example, I have some JSON with a bunch of brands…
And I want to access the number of brands so I can create entitities for each brand later on.
I thought it might be something like this:
but that just returns undefined.
To do that use the following native method:
// this will get the number of properties in the current pc.Application instance
July 13, 2021, 6:33pm
Not exactly, I think that would give me a count of ALL the nodes but I want to get the count of a specific node within the JSON. In this example its ‘brands’ but I might want to get the amount of different colours or product types etc…
Not sure I follow sorry, wouldn’t this work in your case?
const brandsCount = Object.keys(this.appManagerScript.mattressData.brands).length
To get purple count:
const purpleCount = Object.keys(this.appManagerScript.mattressData.brands.Purple).length
July 13, 2021, 6:49pm
Yes, that seems to work. Do you know also how I can return the name of a child node. I want to loop through the brands and get the name of each (unfortunately in the JSON they aren’t in an array…just child nodes)
You can do that easily using an ES6 method, map(). I don’t know your JSON structure but let’s say name is
// --- this will return an array with all purple products names
const purpleNames = this.appManagerScript.mattressData.brands.Purple.map(o => o.name);
If you don’t want to use map, then you can loop using