Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to count appearance of a given key in nested object

I have a data where the key count appears 6 times and it is nested. I’m trying count the number of times it appears with below logic but somewhat I’m close to it not got the exact result.

The problem is child values I’m getting as 7 which I have consoled. but the final count is always 1 seriously I don’t know why I’m getting 1. Any help!

let data = [{
  "id": "1",
  "child": [
    {
      "id": "12",
      "child": [
        {
          "id": "123",
          "child": [
           {
            "id": "1234"
           }
          ]
        }
      ]
    },
    {
      "id": "2",
      "child": [
        {
          "id": "22"
        }
      ]
    },
    {
      "id": "3"
    },
    {
      "id": "4",
      "child": [
        {

          "id": "42",
          "child": [
            {

              "id": "43"
            }
          ]
        }
      ]
    }
  ]
}]

const countChild = (arr,cnt = 0) => {
  for (const {child} of arr) {
    cnt = cnt + 1
    console.log("child",cnt)
    if(child) countChild(child, cnt)
  }
  return cnt;
};
console.log("Final count",countChild(data))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would recommend a reduce function for that:

const countData = (arr: any) => {
    return arr.reduce((results: number, elm: any) => {
        if (!!elm.child) {
            results += (1 + countData(elm.child));
        }

        return results;
    }, 0);
};

But if you still want to use your function, it needs to be adapted as below:

const countChild = (arr,cnt = 0) => {
  for (const {child} of arr) {
    if (child)
        cnt = 1 + countChild(child, cnt);
    console.log("child",cnt)
  }
  return cnt;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading