How can I get a value from an array?

Issue

i get info from my Api in ASP.netCore
in angular i have this :

0: {Id: 3, Role_Name: 'ITAdmin'}
1: {Id: 4, Role_Name: 'Admin'}
2: {Id: 5, Role_Name: 'user'}

and want to get the value out of that array for my CurrenUser
somthing like this in array or something else

var rolename  = itdamin , admin , user


 var id = 3, 4, 5

for show the rolename and RoleId Separated

thanks for helping me 🙂

Solution

You can use reduce to handle your array and get ids and rules you wish:

// sourse array
const tmp = [{
    Id: 3,
    Role_Name: 'ITAdmin'
  }, {
    Id: 4,
    Role_Name: 'Admin'
  }, {
    Id: 5,
    Role_Name: 'user'
  },
];

// default empty target object
const defaultList = {
  ids: [],
  roles: [],
};

// handler of your sourse array
const reducedObj = tmp.reduce((obj, item) => {
  // getting id and role from array item
  const {Id, Role_Name} = item;
  
  // update list
  return {
    ids: [...obj.ids, Id],
    roles: [...obj.roles, Role_Name]
  };
}, defaultList);

// getting ids and roles from reduced object
const {ids, roles} = reducedObj;

console.log('ids: ', ids);
console.log('roles: ', roles);

Simpler way:

// sourse array
const tmp = [{
    Id: 3,
    Role_Name: 'ITAdmin'
  }, {
    Id: 4,
    Role_Name: 'Admin'
  }, {
    Id: 5,
    Role_Name: 'user'
  },
];

// default empty target arrays
const ids = [];
const roles = [];

// handler of your sourse array
tmp.map(item => {
  // getting id and role from array item
  const {Id, Role_Name} = item;
  
  // update lists
  ids.push(Id);
  roles.push(Role_Name);
});

console.log('ids: ', ids);
console.log('roles: ', roles);

Answered By – Yaroslav Trach

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.