0

I am getting Data from my db And I want to loop as required

I am getting array of objects from my data base and I want to convert it to objects with some changes

My Data

 Data=   [
  {
    "Menu": "Menu1",
    "SubMenu": "dash",
    "PATH": "Path1"
  },
  {
    "Menu": "Menu2",
    "SubMenu": "SubMenu1",
    "PATH": "path2"
  },
  {
    "menu": "menu2",
    "SubMenu": "SubMenu2",
    "PATH": "path3"
  },
  {
    "Menu": "menu2",
    "Submenu": "SubMenu3",
    "PATH": "Path4"
  }
]

I want to convert it into like below -:

    {
  "menu1": [
    {
      "SubMenu": "dash",
      "PATH": "path1"
    }
  ],
  "menu2": [
    {
      "SubMenu": "subMenu1",
      "PATH": "Path2"
    },
    {
      "SubMenu": "Submenu2",
      "PATH": "Path3"
    },
    {
      "type": "SubMenu3",
      "link": "Path4"
    }
  ]
}




const newArray= Data.map(element => element.Menu);
console.log(newArray);
manish thakur
  • 760
  • 9
  • 35
  • 76
  • 1
    Does this answer your question? [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) – AZ_ Jan 03 '20 at 10:47

3 Answers3

2

You can use Array.reduce():

var Data = [{
    "Menu": "Menu1",
    "SubMenu": "dash",
    "PATH": "Path1"
  },
  {
    "Menu": "Menu2",
    "SubMenu": "SubMenu1",
    "PATH": "path2"
  },
  {
    "Menu": "Menu2",
    "SubMenu": "SubMenu2",
    "PATH": "path3"
  },
  {
    "Menu": "Menu2",
    "SubMenu": "SubMenu3",
    "PATH": "Path4"
  }
];

var res = Data.reduce((acc, item) => {
  var accObj = {
    Submenu: item.SubMenu,
    PATH: item.PATH
  };
  if(acc[item.Menu]) {
    acc[item.Menu].push(accObj);
  } else {
    acc[item.Menu] = [accObj];
  }
  return acc;
}, {});

console.log(res);
Ankita Kuchhadiya
  • 1,255
  • 6
  • 16
0

You're in the right direction with map, however you should initialise an object before you iterate (result = {}) and populate it as you go. You'd then not use .map but .forEach because you won't be using the output.

const result = {}
Data.forEach(item => result[item.Menu] = {
    //...
})
Sheraff
  • 5,730
  • 3
  • 28
  • 53
0

Try for this:

var obj = {};
  Data.forEach(function(element){
    var menu = element["Menu"];
    delete element["Menu"];
    if(Object.keys(obj).includes(menu)){            
        obj[menu].push(element)
    } else {            
        obj[menu] = [element]
    }
  })   
  console.log("oo", obj);

OUTPUT:

{
    Menu1: [{
        SubMenu: 'dash',
        PATH: 'Path1'
    }],
    Menu2: [{
            SubMenu: 'SubMenu1',
            PATH: 'path2'
        },
        {
            SubMenu: 'SubMenu2',
            PATH: 'path3'
        },
        {
            Submenu: 'SubMenu3',
            PATH: 'Path4'
        }
    ]
}
Subburaj
  • 5,114
  • 10
  • 44
  • 87