title: Sum children multiple values and save result to parent in n-ary tree in Javascript
body: <p>I asked this: <a href="https://stackoverflow.com/questions/52533029/sum-children-values-and-save-result-to-parent-in-n-ary-tree-in-javascript/">Sum children values and save result to parent in n-ary tree in Javascript</a></p>
  
  <p>And I recieved an answer from @Nina Scholz. Now I am trying to use the same code but with more than one value, for instance: </p>
  
  <pre><code>value: {A: 1, B: 2, C: 3}
  </code></pre>
  
  <p>I tried something like this:</p>
  
  <pre><code>function update(array) {
     var root = [],
        references = array.reduce((r, o) =&gt; {
           if (!o.parents.length) {
              root.push(o.id);
           }
           r[o.id] = o;
           return r;
        },Object.create(null));
  
     root.reduce(
     function sum(s, id) {
       var o = references[id];
  
       for (var key in o.value) {
         return s + (o.value[key] = o.children.reduce(sum, 0) || o.value[key])
       }
     }, 0);
  
     return array;
  }
  
  var data2 = [{ id: 'A', parents: [], children: ['B', 'E'], value: {A:1, B:2} }, { id: 'B', parents: ['A'], children: ['C', 'D'], value: {A:1, B:2} }, { id: 'C', parents: ['B'], children: [], value: {A:1, B:2} }, { id: 'D', parents: ['B'], children: [], value: {A:1, B:2} }, { id: 'E', parents: ['A'], children: ['F'], value: {A:1, B:2} }, { id: 'F', parents: ['E'], children: [], value: {A:1, B:2} }]
  
  console.log(update(data2));
  </code></pre>
  
  <p>But only works with the value A because of the return.</p>
  
  <p>Another thing I tried:</p>
  
  <pre><code>function update(array) {
     var root = [],
        references = array.reduce((r, o) =&gt; {
           if (!o.parents.length) {
              root.push(o.id);
           }
           r[o.id] = o;
           return r;
        },Object.create(null));
  
     root.reduce(
     function sum(s, id) {
       var o = references[id];
  
       var x;
       for (var key in o.value) {
          x = (s + (o.value[key] = o.children.reduce(sum, 0) || o.value[key]));
       }
     }, 0);
  
     return array;
  }
  
  var data2 = [{ id: 'A', parents: [], children: ['B', 'E'], value: {A:1, B:2} }, { id: 'B', parents: ['A'], children: ['C', 'D'], value: {A:1, B:2} }, { id: 'C', parents: ['B'], children: [], value: {A:1, B:2} }, { id: 'D', parents: ['B'], children: [], value: {A:1, B:2} }, { id: 'E', parents: ['A'], children: ['F'], value: {A:1, B:2} }, { id: 'F', parents: ['E'], children: [], value: {A:1, B:2} }]
  
  console.log(update(data2));
  </code></pre>
  
  <p>But it does not work with the ones that have children.</p>