let obj = {
key1: {
a: 1, b: 2,
c: {
d: 3,
e: 4,
},
f: 5
},
key2: {
g: 6, h: 7
}
};
let sum = 0;
for (key1 in obj) {
for (key2 in obj[key1]) {
for (key3 in obj[key1][key2]) {
for (key4 in obj[key1][key2][key2]) {
sum += key4;
}
}
}
}
console.log(sum);
В чем моя ошибка?
const sum = val =>
val instanceof Object
? Object.values(val).reduce((acc, n) => acc + sum(n), 0)
: typeof val === 'number'
? val
: 0;
console.log(sum(obj));
function sum(val) {
let result = 0;
for (const stack = [ val ]; stack.length;) {
const n = stack.pop();
if (n instanceof Object) {
stack.push(...Object.values(n));
} else if (n === +n) {
result += n;
}
}
return result;
}