How to find sum of a specific property in nested JS object

I want to calculate the total sum of all the 'val' in this object. The final output should be 113. I tried searching but couldn't find a similar problem on stackoverflow.

const object = {
  val: 10,
  child: [
    {
      val: 20,
      child: [
        {
          val: 25,
          child: []
        },
        {
          val: 28,
          child: []
        }
      ]
    },
    {
      val: 30,
      child: []
    }
  ]
};

What I tried is this. I know this is not the best approach and would love to see a better approach to this.

const object = {
  val: 10,
  child: [
    {
      val: 20,
      child: [
        {
          val: 25,
          child: []
        },
        {
          val: 28,
          child: []
        }
      ]
    },
    {
      val: 30,
      child: []
    }
  ]
};

function sum() {
 let k = object.val;
 if(object.child.length>0){
 object.child.map(item => {
 
 k += item.val;
 if(item.child.length>0){
 item.child.map(item => k += item.val)
 }
 })
 }
 
 return k
}

const result = sum(object);
console.log(result);

You can find the problem here - https://codesandbox.io/s/young-night-ulnfl?file=/src/index.js

I was also thinking something like flat() could have helped but that is only for arrays.



Read more here: https://stackoverflow.com/questions/68469859/how-to-find-sum-of-a-specific-property-in-nested-js-object

Content Attribution

This content was originally published by Nitin Gupta at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: