I am trying to process an array in angular. I need to get admin user name from an array and trying below approach
export class AppComponent { adminName = '' data = { id:1, name:'Test User One', users:[ {id:1,name:'User 2',role:'Management Admin'}, {id:2,name:'User 3',role:'User'}, {id:3,name:'User 1',role:'Profile Admin'}, ] } ngOnInit(){ this.getAdminName(this.data.users) } getAdminName(users){ let name = '' name = users.filter((user)=>{ user.role = user.role.replace(/\s/g, '-').toUpperCase() return user.role === 'PROFILE-ADMIN' }).map(row=>{ return row.name }) this.adminName = name[0] } } This is working and i am able to get adminName but it also changes role of data object and converts object like this
{ "id": 1, "name": "Test User One", "users": [ { "id": 1, "name": "User 2", "role": "MANAGEMENT-ADMIN" }, { "id": 2, "name": "User 3", "role": "USER" }, { "id": 3, "name": "User 1", "role": "PROFILE-ADMIN" } ] } I understand why this happened and i tried using spread operator but it is not working i tried below approach
Approach one
this.getAdminName([...this.data.users]) // passing from here using spread operator Approach Second
getAdminName(users){ let usersList = [...users] let name = '' name = usersList.filter((user)=>{ user.role = user.role.replace(/\s/g, '-').toUpperCase() return user.role === 'PROFILE-ADMIN' }).map(row=>{ return row.name }) this.adminName = name[0] } I am able to do it like below
getAdminName(users){ let name = '' let role; name = users.filter((user)=>{ role = user.role //used a variable in which holds role = role.replace(/\s/g, '-').toUpperCase() return role === 'PROFILE-ADMIN' }).map(row=>{ return row.name }) this.adminName = name[0] } But I want to do it using spread Operator approach so Please suggest me where i am going wrong
Stackblitz link is here
user.role = user.role.replace(/\s/g, '-').toUpperCase()this will modify the user role. Can you not check without assigining it touser.role?user.role = user.role.replace(/\s/g, '-').toUpperCase(), no amount of spread operators will give the desired result