0

I have this object:

[
 {
    id: 1,
    child: false,
    link_type: expand
 },
 {
    id: 2,
    child: true,
    url: /home,
    link_type: direct,
    parent: 1
 },
 {
    id: 3,
    child: false,
    url: /settings,
    link_type: direct
 }
]

I want to do nesting of the object in such a way that the final output will be:

[
  {
    id: 1,
    link_type: expand,
    child: [
        {
            id: 2,
            url: /home,
           link_type: direct,
           parent: 1
        }
      ]
 },
 {
   id: 3,
   url: /settings,
   link_type: direct
 }
]

note: the orignal data has other fields I have included fields that are needed.

I have tried creating a nesting like this for parent node:

this.sideMenuService.getAll().subscribe(d => {
         console.log(JSON.stringify(d));
         let data: SideMenuList = {};
         let count = 0;
         d.forEach(e => {
            if (!e.child) {
               // console.log(count);
               // console.log(e.menu_id);
               data.menu_id = e.menu_id;
               data.displayname = e.displayname;
               data.iconcss = e.iconcss;
               data.link_type = e.link_type;
               data.sequence = e.sequence;
               data.url = e.url;
               console.log(data);
               this.sideMenuList.push(data);
               // console.log(this.sideMenuList);
               count++;
            }
         });
         console.log(this.sideMenuList);
});

But i am getting output like this: output

Any help will be appreciated.

1 Answer 1

2

You can use Array.reduce() to iterate over the data and create a new nested array as followings.

But your data is invalid. Please note the quotation marks added to the data

const data = [{
    id: 1,
    child: false,
    link_type: "expand"
  },
  {
    id: 2,
    child: true,
    url: "/home",
    link_type: "direct",
    parent: 1
  },
  {
    id: 3,
    child: false,
    url: "/settings",
    link_type: "direct"
  },
  // This one is added to show multi-level nest
  {
    id: 4,
    child: true,
    url: "/settings",
    link_type: "direct",
    parent: 2
  }
]

const denormalized = data.reduce((acc, cur) => {
  if (!cur.parent) {
    acc.push(cur)
  }
  const children = data.filter(child => child.parent === cur.id)
  if (children.length > 0) {
    cur.children = children
  }
  return acc;

}, [])

console.log(denormalized)

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

1 Comment

Can you help with the source where I can find stuff like this ? Thanks in advance.

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.