"mainData"{
entities:[]
},
"data2":{
entities:[
{
name:"mainData": //entites
},
{
name:"mainData": //entites
},
{
name:"mainData": //entites
},
]
},
"data3":{
entites:[
{
name:"data2": //entites
},
{
name:"data2": //entites
},
{
name:"data2": //entites
},
{
name:"data2": //entites
},]
}
I have a data like this what i want to do is add count in each object that is related with mainData for example like this data2.entities has 3 main data in it so count should be 3 and then data3.entites has 4 data2s in it so data3s count should be 12 cause data2 has 3 mainData inside it
edit:How does data3 count become 12?
cause data3 has 4 data2s in entities and data2 has 3 mainData in entities so data3s count is 12 on the mainData count
I would like to get output like this
"mainData"{
entities:[]
},
"data2":{
count:3,
entities:[
{
name:"mainData": //entites
},
{
name:"mainData": //entites
},
{
name:"mainData": //entites
},
]
},
"data3":{
count:12,
entites:[
{
name:"data2": //entites
},
{
name:"data2": //entites
},
{
name:"data2": //entites
},
{
name:"data2": //entites
},]
}
3
Answers
You can use a recursive approach to count the nested entities.
First, create a function that takes an object and a key as arguments. This function will traverse the object and count the occurrences of the key in the nested entities.
How it works?
If the object is an array, iterate over each element and call the function recursively.
If the object is an object and it has a property named
name
that matches the key, increment the count.If the object is an object and it has a property named
entities
, call the function recursively on theentities
property and return thecount
.Sample approach;
You can do something like this:
What this does is to check each
entities
‘sname
and go through the object to find that property’scount
, if it doesn’t have one and itsentities
array is empty, the count is considered1
. Also, if it doesn’t have one and theentities
array is not empty, calculate this object’scount
first.You can recurse: