-2

I need convert this code to loops , but i have no idea how .

let object = {
  x: 250,
  a: 5,
  b: 5,
  c: {
    ac: 5,
    acd: 10
  }
};

let objectPropertiesSum = object => {
  let sum = 0;
  for (const value of Object.values(object)) {
    if (typeof(value) === "number") {
      sum += value;
    } else if (typeof(value) === "object") {
      sum += objectPropertiesSum(value);
    }
  }
  return sum;
};
console.log(objectPropertiesSum(object));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
KrisKong
  • 11
  • 1
  • "*I need convert this code to loops*" - no you don't. A recursive approach is perfectly appropriate here. – Bergi Feb 18 '22 at 14:00
  • @mplungjan This question is not about arrays though, I don't think the duplicate is appropriate – Bergi Feb 18 '22 at 14:02
  • @Bergi I understand, but this is my homework – KrisKong Feb 18 '22 at 14:03
  • 1
    @KrisKong Then surely you learned in class how to approach this (e.g. with a queue). If you show us your attempt at a solution, we can help you find and fix the problem, but StackOverflow is not a homework service. Please [edit] your question and I'll reopen. – Bergi Feb 18 '22 at 14:04
  • @Bergi my task was : "to implement function that will count sum of all object properties that are numbers! " And i write this , now i trying to do same but witih loops – KrisKong Feb 18 '22 at 14:12

1 Answers1

1

Where are you getting stuck? Maybe this can help you get started.

function sumValues(obj) {
  const stack = [obj]
  let sum = 0
  let o, v
  while (stack.length) {  /* as long as there are items on the stack */
    o = /* get an item off the stack */
    for (v of /* obj values */) {
      if (/* v is a number */)
        /* update the sum */
      else if (/* v is an object */)
        /* update the stack */
      else
        /* v is not a Number or an Object */
    }
  }
  return sum
}
よつば
  • 467
  • 1
  • 8