0

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

2 Answers2

2

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);
Yaroslav Trach
  • 1,833
  • 2
  • 12
  • 18
1

Now you can found an edit code which print 2 arrays

let id = []
let role = []
const input = [{
    Id: 3,
    Role_Name: 'ITAdmin'
}, {
    Id: 4,
    Role_Name: 'Admin'
}, {
    Id: 5,
    Role_Name: 'user'
}, ];

for (let index = 0; index < input.length; index++) {
    id[index] = input[index].Id;
    role[index] = input[index].Role_Name
}
console.log(id)
console.log(role)