Home > OS >  Group nested object using lodash
Group nested object using lodash

Time:03-19

I have object like this.

  data = [
{
  id: "0",
  name: "maths",
  levelNo: 0,
  level: null
},
{
  id: "15",
  name: "sceince",
  levelNo: 0,
  level: null
},
{
  name: "algebra",
  id: "1",
  parentId: "0",
  levelNo: 1,
  level: {
    id: "0",
    name: "maths"
  }
},
{
  name: "alfunction",
  id: "2",
  parentId: "1",
  levelNo: 2,
  level: {
    id: "1",
    name: "alegera"
  }
},
{
  name: "bhumiti",
  id: "3",
  parentId: "1",
  levelNo: 2,
  level: {
    id: "1",
    name: "alegera"
  }
},
{
  name: "paryavan",
  id: "4",
  parentId: "0",
  levelNo: 1,
  level: {
    id: "0",
    name: "maths"
  }
},
{
  name: "trikon",
  id: "5",
  parentId: "3",
  levelNo: 3,
  level: {
    id: "3",
    name: "bhumiti"
  }
}];

and convert this object into

  subject = [
{
  name: "maths",
  id: "0",
  items: [
    {
      id: "1",
      name: "alegera",
      items: [
        {
          name: "alfunction",
          id: "2"
        },
        {
          name: "bhumiti",
          id: "3",
          items: [
            {
              name: "trikon",
              id: "5"
            }
          ]
        }
      ]
    },
    {
      id: "4",
      name: "paryavan"
    }
  ]
}];

CodePudding user response:

You could take a function which uses parentId and id without levelNo and level.

const
    getTree = (data, root) => {
        const t = {};
        data.forEach(({ parentId, levelNo, level, ...o }) =>
            ((t[parentId] ??= {}).children ??= []).push(Object.assign(t[o.id] ??= {}, o))
        );
        return t[root].children;
    },
    data = [{ id: "0", name: "maths", levelNo: 0, level: null }, { id: "15", name: "sceince", levelNo: 0, level: null }, { name: "algebra", id: "1", parentId: "0", levelNo: 1, level: { id: "0", name: "maths" } }, { name: "alfunction", id: "2", parentId: "1", levelNo: 2, level: { id: "1", name: "alegera" } }, {  name: "bhumiti", id: "3", parentId: "1", levelNo: 2, level: { id: "1", name: "alegera" } }, { name: "paryavan", id: "4", parentId: "0", levelNo: 1, level: { id: "0", name: "maths" } }, { name: "trikon", id: "5", parentId: "3", levelNo: 3, level: { id: "3", name: "bhumiti" } }],
    tree = getTree(data);

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related