Search code examples
javascriptarrayslodash

How to add the values of the children object and push it to the corresponding parent


I have a json structure as below

[{ "name": "minpur", "children": [{ "name": "ppp1", "children": [{ "name": "feeder", "children": [{ "name": "rmu16", "children": [{ "name": "invt16", "children": [{ "aname": "inv 01", "value": 300 }, { "aname": "inv 03", "value": 500 }] }] }] }] }] }]

i want to add the value of children object and push to the corresponding parent like below

[{ "name": "minpur", "value": 800, "children": [{ "name": "ppp1", "value": 800, "children": [{ "name": "feeder", "value": 800, "children": [{ "name": "rmu16", "value": 800, "children": [{ "name": "invt16", "value": 800, "children": [{ "aname": "inv 01", "value": 300 }, { "aname": "inv 03", "value": 500 }] }] }] }] }] }]


Solution

  • You can create a recursive function that iterates the children, and adds the value according to their children, etc...

    Note: the value property in the example appears after the children property.

    const fn = arr => arr.map(o => {
      if(!o.children) return o
      
      const children = fn(o.children)
      const value = (o.value || 0) + children.reduce((r, { value }) => r + value, 0)
      
      return {
        ...o,
        value,
        children
      }
    })
    
    const data = [{"name":"minpur","children":[{"name":"ppp1","children":[{"name":"feeder","children":[{"name":"rmu16","children":[{"name":"invt16","children":[{"aname":"inv 01","value":300},{"aname":"inv 03","value":500}]}]}]}]}]}]
    
    const result = fn(data)
    
    console.log(result)