Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a deeply nested object

I have the following object

const categories = [
  {
    id: 1,
    name: "Main",
    parent: null
  },
  {
    id: 2,
    name: "Computers",
    parent: 1
  },
  {
    id: 3,
    name: "Components",
    parent: 2
  },
  {
    id: 4,
    name: "RAM",
    parent: 3
  }
];

I would like it to return the following format

{
    "id": 4,
    "name": "RAM",
    "parent": {
        "id": 3,
        "name": "Components",
        "parent": {
            "id": 2,
            "name": "Computers",
            "parent": {
                "id": 1,
                "name": "Main",
                "parent": null
            }
        }
    }
}

This is the code I have for now

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const recursiveBuild = (node) => {
  console.log(node);
  if (node.parent === null) {
    return node;
  }
  const parent = categories.find((cat) => cat.id === node.parent);
  node.parent = parent;
  return recursiveBuild(node.parent);
};

const item4 = categories.find((cat) => cat.id === 4);
const res = recursiveBuild(item4);

The end result is that I have traversed to the the beginning

{id: 1, name: 'Main', parent: null}

I believe I am very close, but still cant crack it yet. Appreciate if someone can help, thank u

>Solution :

Indeed, you are very close.

You need to change this line:

return recursiveBuild(node.parent);

to these lines:

recursiveBuild(node.parent);
return node;

Here is the working snippet:

const categories = [
  {
    id: 1,
    name: "Main",
    parent: null
  },
  {
    id: 2,
    name: "Computers",
    parent: 1
  },
  {
    id: 3,
    name: "Components",
    parent: 2
  },
  {
    id: 4,
    name: "RAM",
    parent: 3
  }
];

const recursiveBuild = (node) => {
  
  if (node.parent === null) {
    return node;
  }
  const parent = categories.find((cat) => cat.id === node.parent);
  node.parent = parent;
  
  // return recursiveBuild(node.parent);
  recursiveBuild(node.parent);
  return node;
};

const item4 = categories.find((cat) => cat.id === 4);
const res = recursiveBuild(item4);

console.log(res);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading