this is persons object how can I add all ages in here if the object were dynamic. I tried to do it with recursion but not succeded any body can help , I tried to achieve it by reduce method of javascript but can't get the logic how to return value and add continuously to get result
enter code here
const persons = {
name: "Tom",
age: 70,
kids: [
{
name: "Jerry",
age: 40,
kids: [
{
name: "Jack",
age: 10,
kids: [
{
name: "take",
age: 10,
},
{
name: "Note",
age: 5,
},
],
},
{
name: "atleast",
age: 5,
},
],
},
],
};
here is my code
let sum = 0;
const red = (arr) => {
sum += arr.reduce((total, b) => {
if (b.kids) {
red(b.kids);
}
return total + b.age;
}, sum);
console.log(sum);
};
red(persons.kids);