Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum the values in this object of objects in javascript?

Tags:

javascript

const ob = {
    a: 1,
    b: {
        c: 3,
        d: 6,
        e: {
            f: {
                g: 3,
                h: {
                    i: 5,
                    j: {
                        k: 7
                    }
                }
            }
        }
    }
};

Any methods to solve this code?

I have no idea how to solve this code.

For abovementioned input I would expect a result of 1 + 3 + 6 + 3 + 5 + 7 = 25. So what I want to return from a function sumObject(ob) is: 25

like image 301
Santhosh Kumar Avatar asked Feb 02 '26 21:02

Santhosh Kumar


2 Answers

You can try reduce with recursion

The condition for the sum is

  • If the current value is a number, sum it with result
  • If the current value is not a number (in your case, it's an object), call the function sumObject recursively with current result

const ob = {
  a: 1,
  b: {
    c: 3,
    d: 6,
    e: {
      f: {
        g: 3,
        h: {
          i: 5,
          j: {
            k: 7
          }
        }
      }
    }
  }
};

function sumObject(data, result = 0) {
  return Object.values(data).reduce((sum, value) => typeof value === 'number' ? sum + value : sumObject(value, sum), result)
}

console.log(sumObject(ob))
like image 121
Nick Vu Avatar answered Feb 04 '26 11:02

Nick Vu


If you don't understand some of the other answers, this is an easier solution to understand:

function sumObject(obj){
  
  let result = 0;
  
  for(let i of Object.values(obj)){ //we iterate through all values in obj
    
    if(typeof i == "number"){ //if the current value of i is a number
      
      result+=i; //then add that to the result
      
    } else { //otherwise, it will be an object
      
      result+=sumObject(i); //so we call the function on itself to iterate over this new object
      
    }
    
  }
  
  return result; //finally, we return the total
  
}

console.log(sumObject(ob));
like image 23
KoderM Avatar answered Feb 04 '26 11:02

KoderM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!