-1

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.

2
  • Please add the code you've attempted to your question as a minimal reproducible example. Commented Dec 16, 2022 at 11:03
  • @Andy I have added a solution I tried. Commented Dec 16, 2022 at 13:09

1 Answer 1

0

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.