TransWikia.com

How do I show the value of an array that has another array inside?

Stack Overflow Asked by dany952 on February 2, 2021

How do I loop through this array and how do I display this roleName value want to loop through it with map

{ 
   "userMenuDTO": {    
        "menuId": "13",
        "menuName":"PruebaMenu900-13",
        "menuRoute":"/path/ruta900-13",
        "menuParentId":null,
         "menuDinamico": true,
        "menuEnabled": false,
        "menuPosition": 900,
        "menuIcono":"pruebaIcono",
        "roles": [
            {
                "roleId": 1,
                "roleName": "CO-MOCA-ADMIN",
                "roleType": 1
            },
             {
                "roleId": 2
                
            }
        ]
    }
}

2 Answers

For the iteration, you can use forEach and map

const {roles} = userData.userMenuDTO; // Object destructuring

// forEach won't return any result so that we have to push to an array.
const result = [];
roles.forEach(role => result.push(role.roleName)); // using arrow function here
console.log(result);

// Map will return result as array. (more preferable approach)
var rollNamesArr = roles.map(role => role.roleName);
console.log(rollNamesArr);

Answered by Sarun UK on February 2, 2021

I see this JSON object has roles array inside this and you can directly access the roles array.

You can you mapper in this case and extract role names into new array and use it, just one of many ways to do this.

var userData = {
  "userMenuDTO": {
    "menuId": "13",
    "menuName": "PruebaMenu900-13",
    "menuRoute": "/path/ruta900-13",
    "menuParentId": null,
    "menuDinamico": true,
    "menuEnabled": false,
    "menuPosition": 900,
    "menuIcono": "pruebaIcono",
    "roles": [{
        "roleId": 1,
        "roleName": "CO-MOCA-ADMIN-1",
        "roleType": 1
      },
      {
        "roleId": 2,
        "roleName": "CO-MOCA-ADMIN-2",
        "roleType": 2
      },

      {
        "roleId": 3,
        "roleName": "CO-MOCA-ADMIN-3",
        "roleType": 3
      }
    ]
  }
};

var rollNamesArr = userData.userMenuDTO.roles.map(function(role) {
    return role.roleName;
});

console.log(rollNamesArr);

Answered by harishprodduturi on February 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP