Skip to content
Advertisement

How to transform nested object of objects into array of objects

Hi all I have the following code

the data that I want to transform.

    const obj = {

     numbers: {
      label: "main numbers",
      pageTitle: "Numbers",
      key: "1",
        items: {
          firstNumber: {
            label: "first number",
            pageTitle: "first",
            key: "first"
           },
         secondNumber: {
            label: "second number",
            pageTitle: "second",
            key: "second"
           }  
        }
     },

    letters: {
      label: "main Letters",
      pageTitle: "Letters",
      key: "2",
         items: {
           firstLetter: {
            label: "first Letter",
            pageTitle: "first",
            key: "first"
         }
       }
     },

    signs: {
       label: "main sign",
       pageTitle: "Sign",
       key: "3"
    }
 };

In my obj variable I have 3 other objects

numbers object which has items property which includes 2 other objects.

letters object which has items property which includes only one object.

signs object.

I need to transform my obj to the following way.

    [
      {
        label:"main numbers", 
        pageTitle:"Numbers", 
        key:1, 
        children: [{label,pageTitle,key},{label,pageTitle,key}] 
      },
      {
        label:"main Letters", 
        pageTitle:"Letters", 
        key:1, 
        children: [{label,pageTitle,key}] 
      },
     {
        label:"main sign", 
        pageTitle:"Sign", 
        key:1, 
        children: [] 
      },


    ]

for that transformation, I wrote the following code.

    const transformedData = Object.values(obj).map((menuitem) => menuitem);

    const data = [];

    transformedData?.map((x) => {
      const newData = {};
      newData.label = x.label;
      newData.pageTitle = x.pageTitle;
      newData.key = x.key;
      newData.children = x?.Object?.values(items)?.map((el) => {
        newData.children.label = el.label;
        newData.children.pageTitle = el.pageTitle;
        newData.children.key = el.key;
      });
      data.push(newData);
    });

Everything was working, but for children instead of printing an array it prints undefined.

Please help me to resolve this issue.

Advertisement

Answer

I created a function for your case.

    const convert = data =>
      Object.values(data)?.map(x => ({
       label: x.label,
       pageTitle :x.pageTitle ,
       key: x.pathname,
        children: x.items
          ? Object.values(x.items || {}).map(el => ({ label: el.label, 
            key:el.pathname,pageTitle:el.pageTitle  }))
         : null,
      }));

You can use like const items = convert(obj).

Advertisement