1

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
  • its an object. all you have to do is obj.userMenuDTO.roles.map(item => <p> {item.roleName} </p>) Commented Sep 26, 2020 at 3:25
  • you'd loop through x.userMenuDTO.roles - where x is the name of the variable that object is in ... by the way, there is only a single array, there's no array inside another array in the data you posted Commented Sep 26, 2020 at 3:26

2 Answers 2

1

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

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

Comments

0

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

Comments

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.