dany952
dany952

Reputation: 329

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

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
                
            }
        ]
    }
}

Upvotes: 1

Views: 69

Answers (2)

harishprodduturi
harishprodduturi

Reputation: 46

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);

Upvotes: 1

Sarun UK
Sarun UK

Reputation: 6766

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);

Upvotes: 0

Related Questions