Home > Software engineering >  transform nested object into another tree
transform nested object into another tree

Time:03-31

I've been trying to transform nested object to another tree object but without success. I can't figure out its solution, so any help would be appreciated.

Expected output

[
    {
        "duration": 2117538,
        "duration_min": 1001,
        "duration_max": 201530,
        "input": 0,
        "output": 0,
        "label": "down",
        "id": "0",
        "children": [
            {
                "duration": 211538,
                "duration_min": 1001,
                "duration_max": 201530,
                "input": 0,
                "output": 0,
                "boxes": 0,
                "label": "other",
                "id": "0-1",
                "children": [
                    {
                        "duration": 1538,
                        "duration_min": 1001,
                        "duration_max": 201530,
                        "input": 0,
                        "output": 0,
                        "boxes": 0,
                        "id": "0-1-0",
                        "label": "no resource",
                    },
                  
                ]
            }
        ]
    }
]

As you can see, object's descendants are put into children and consequent id field was added. And in the example below, we have an object which consists of values key and its children, which is other. Deep down, there is no resource key that only has values key which means there will be no children array.

Let's see input format and its structure. In data object, there is key down and its value, which is an object. Inside that object there are values and other. Keys that is not values, are put into children.

Given input

const data = {
  "down": {
      "values": {
          "duration": 2117538,
          "duration_min": 1001,
          "duration_max": 201530,
          "input": 0,
          "output": 0,
          "boxes": 0,
      },
      "other": {
          "no resource": {
              "values": {
                  "duration": 1538,
                  "duration_min": 1001,
                  "duration_max": 201530,
                  "input": 0,
                  "output": 0,
                  "boxes": 0,
              }
          },
          "values": {
              "duration": 211538,
              "duration_min": 1001,
              "duration_max": 201530,
              "input": 0,
              "output": 0,
              "boxes": 0,
          }
      }
  }
}

What I tried

function getTransformData(object, name = 'total') {
    return Object.entries(object).map(function ([key, value]) {
      
      if (key === 'values') {
        return { ...value, label: name };
      }
      
      if (value.values) {
        return { ...value.values, label: key, children: getTransformData(value, key) };
      }

    });
}


console.log(getTransformData(data))

But this doesn't work as needed.

CodePudding user response:

Issue has been solved.

function transformNestedObject({values,...children}, id, duration) {
  duration = duration || values.duration;
  children = Object.entries(children).map(([key, value],i)=>{
      const _id = id ? id  "-"   i : '' i;
      const durationPercent = (value.values.duration / duration * 100.0).toFixed(2)   '%';
      return {
        id: _id,
        label: key,
        durationPercent,
        ...transformNestedObject( value, _id, duration)
      }
    });
    
    if (id) {
      return {...values, children};
    }
    
    return children;
}

console.log(transformNestedObject(data));

CodePudding user response:

Using recursion:

function to_tree(d, c = []){
   var r = {false:[], true:[]}
   var vals = []
   var k = 0;
   for (var i of Object.keys(d)){
     r[i === 'values'].push(d[i])
   }
   for (var i of r[true]){
     vals.push({...i, 'id':[...c, k].map(x => x.toString()).join('-')});
     k  ;
   }
   for (var i of r[false]){
      if (vals.length){
         vals[vals.length-1]['children'] = to_tree(i, [...c, k])
      }
      else{
         vals = [...vals, ...to_tree(i, c)]
      }
   }
   return vals
}
  • Related