Convert JSON tree nodes into final JSON recursively

167 views Asked by At

I need help to convert this json tree nodes to final json structure joining the nodes recursively. Any help is appreciated. I need a recursively function in javascript. Given below the sample input and output I needed. My Input

{
  root: {
    parent_id: 'root',
    current_id: 'root',
    children: ['node_233443'],
    type: 'stack',
  },
  node_233443: {
    parent_id: 'root',
    current_id: 'node_233443',
    children: ['node_fdfd33', 'node_hd44d4'],
    type: 'column',
  },
  node_fdfd33: {
    parent_id: 'node_233443',
    current_id: 'node_fdfd33',
    children: [],
    type: 'text',
  },
  node_hd44d4: {
    parent_id: 'node_233443',
    current_id: 'node_hd44d4',
    children: [],
    type: 'image',
  },
};

My Needed output

{
  parent_id: 'root',
  current_id: 'root',
  children: [{
    parent_id: 'root',
    current_id: 'node_233443',
    children: [{
      parent_id: 'node_233443',
      current_id: 'node_fdfd33',
      children: [],
      type: 'text',
    },
    {
      parent_id: 'node_233443',
      current_id: 'node_hd44d4',
      children: [],
      type: 'image',
    }],
    type: 'column',
  }],
  type: 'stack',
}

This is the solution I got.

const clonedNodes = structuredClone(nodes);

const recurse = (json) => {
  json.children = json.children.map((item) => {
    if(clonedNodes[item]) {
      return recurse(clonedNodes[item])
    }
  }, [])
  return json;
}

console.log(recurse(clonedNodes.root), nodes)

Any help to improve it please.

1

There are 1 answers

0
trincot On

You could map the children arrays to the objects that correspond to the identifiers in those arrays. You may want to first clone your original object so it does not get mutated:

function nest(obj) {
    const clone = Object.fromEntries(Object.entries(obj).map(([k, o]) => [k, {...o}]));
    for (const node of Object.values(clone)) {
        node.children = node.children.map(id => clone[id]); 
    }
    return clone.root;
}

const data = {root: {parent_id: 'root',current_id: 'root',children: ['node_233443'],type: 'stack',},node_233443: {parent_id: 'root',current_id: 'node_233443',children: ['node_fdfd33', 'node_hd44d4'],type: 'column',},node_fdfd33: {parent_id: 'node_233443',current_id: 'node_fdfd33',children: [],type: 'text',},node_hd44d4: {parent_id: 'node_233443',current_id: 'node_hd44d4',children: [],type: 'image',},};
const result = nest(data);
console.log(result);