skip to Main Content
"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


  1. 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?

    1. If the object is an array, iterate over each element and call the function recursively.

    2. If the object is an object and it has a property named name that matches the key, increment the count.

    3. If the object is an object and it has a property named entities, call the function recursively on the entities property and return the count.

    Sample approach;

    let data = {
       "mainData": {
           entities: []
       },
       "data2": {
           entities: [
               {
                   name: "mainData"
               },
               {
                   name: "mainData"
               },
               {
                   name: "mainData"
               }
           ]
       },
       "data3": {
           entities: [
               {
                   name: "data2"
               },
               {
                   name: "data2"
               },
               {
                   name: "data2"
               },
               {
                   name: "data2"
               }
           ]
       }
    };
    
    function countEntities(obj, key) {
       let count = 0;
    
       if (Array.isArray(obj)) {
           for (let i = 0; i < obj.length; i++) {
               count += countEntities(obj[i], key);
           }
       } else if (typeof obj === 'object') {
           if (obj.name === key) {
               count++;
           }
           if (obj.entities) {
               count += countEntities(obj.entities, key);
           }
       }
    
       return count;
    }
    data.data2.count = countEntities(data.data2.entities, "mainData");
    data.data3.count = countEntities(data.data3.entities, "data2") * 3;
    
    console.log(data);
    Login or Signup to reply.
  2. You can do something like this:

    const o = {
      "mainData": {
        entities: []
      },
      "data2": {
        entities: [{
            name: "mainData"
          },
          {
            name: "mainData"
          },
          {
            name: "mainData"
          },
        ]
      },
      "data3": {
        entities: [{
            name: "data2"
          },
          {
            name: "data2"
          },
          {
            name: "data2"
          },
          {
            name: "data2"
          },
        ]
      }
    };
    
    const calcCountFor = (prop) => {
      return o[prop].count = o[prop].entities.reduce((a, c) => {
        let count;
        if (o[c.name].entities.length === 0) {
          count = 1;
        } else if (typeof o[c.name].count !== 'undefined') {
          count = o[c.name].count;
        } else {
          count = calcCountFor(c.name);
        }
        return a + count;
      }, 0)
    }
    
    Object.keys(o).forEach((key) => {
      calcCountFor(key);
    });
    
    console.log(o);

    What this does is to check each entities‘s name and go through the object to find that property’s count, if it doesn’t have one and its entities array is empty, the count is considered 1. Also, if it doesn’t have one and the entities array is not empty, calculate this object’s count first.

    Login or Signup to reply.
  3. You can recurse:

    const calculateCount = (data, name) => (name === "mainData") ? 1 // Base case: mainData has no nested entities, so count is 1
      : data[name].entities.reduce((acc, entity) => (acc + calculateCount(data, entity.name)), 0);  // counts of nested entities
    
    // Calculate and add the count property to each data object
    Object.keys(data).forEach(key => {
      data[key].count = calculateCount(data, key);
    });
    
    console.log(data);
    <script>
      const data = {
        "mainData": {
          entities: []
        },
        "data2": {
          entities: [{
              name: "mainData"
            },
            {
              name: "mainData"
            },
            {
              name: "mainData"
            }
          ]
        },
        "data3": {
          entities: [{
              name: "data2"
            },
            {
              name: "data2"
            },
            {
              name: "data2"
            },
            {
              name: "data2"
            }
          ]
        }
      };
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search