Home > Enterprise >  Create a deeply nested object
Create a deeply nested object

Time:06-30

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

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

CodePudding user response:

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

CodePudding user response:

This works for me:

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

let me know if there are any issues

  • Related