const valueList = {
prop: 'prop1',
value: 150,
children: [
{
prop: 'prop1',
value: 14
}, {
prop: 'prop1',
value: 10,
children: [
{
prop: 'prop1',
value: 14
}, {
prop: 'prop1',
value: 10,
children: []
},{
prop: 'prop1',
value: 110,
}
]
},{
prop: 'prop1',
value: 110,
}
]
}
const sum = data =>
(data instanceof Array ? data : [ data ]).reduce((acc, n) => {
return acc + n.value + sum(n.children || []);
}, 0);
const valueSum = sum(valueList);
function sum(data) {
let result = 0;
for (const stack = [].concat(data); stack.length;) {
const { value, children: c } = stack.pop();
stack.push(...(Array.isArray(c) ? c : []));
result += value;
}
return result;
}