-1

I have a service called UserService that returns the roles of the logged in user.

It returns either [{"authority":"ROLE_APEX_SUPPORT"},{"authority":"ROLE_APEX_READONLY"}] or [{"authority":"ROLE_APEX_READONLY"}].

I want to do something when I see that the response returned has ROLE_APEX_SUPPORT authority in it. How do I parse the response to identify that?

let listOfAuthorities = this.userServices.getAuthorities();

listOfAuthorities is an array of JSON of above mentioned response. How do I parse and see if it has Support role in response?

Derek Jin
  • 652
  • 2
  • 12
  • 29
Sid
  • 55
  • 7

3 Answers3

1

I want to do something when I see that the response returned has ROLE_APEX_SUPPORT authority in it

If I understand your question correctly, you probably want to check if your array has an item with authority: ROLE_APEX_SUPPORT

const input1 = [{
  "authority": "ROLE_APEX_SUPPORT"
}, {
  "authority": "ROLE_APEX_READONLY"
}];

const input2 = [{
  "authority": "ROLE_APEX_READONLY"
}];

function hasAuthority(input, authority) {
  return input.some((i) => i.authority === authority);
}

console.log(hasAuthority(input1, "ROLE_APEX_READONLY"))
console.log(hasAuthority(input2, "ROLE_APEX_SUPPORT"))
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
1

With a little effort you could have found the answer yourself. But, here it is:

let listOfAuthorities = this.userServices.getAuthorities();
let authorityList = JSON.parse(listOfAuthorities);

authorityList.forEach(authority => {
    if(authority.authority === 'ROLE_APEX_SUPPORT') {
    // write your logic here
    }
});
Rohan Agarwal
  • 2,441
  • 2
  • 18
  • 35
0

To check whether your data contains ROLE_APEX_SUPPORT:

const json = [{"authority":"ROLE_APEX_SUPPORT"}, {"authority":"ROLE_APEX_READONLY"}];
const isROLE_APEX_SUPPORT = json.some(s=>s.authority === 'ROLE_APEX_SUPPORT');
console.log(isROLE_APEX_SUPPORT); // Output: true

To find whether your data contains ROLE_APEX_SUPPORT:

const json = [{"authority":"ROLE_APEX_SUPPORT"}, {"authority":"ROLE_APEX_READONLY"}];
const roleAlexSupport = json.find(s=>s.authority === 'ROLE_APEX_SUPPORT');
console.log(roleAlexSupport ); // OUTPUT: {authority: "ROLE_APEX_SUPPORT"}

In addition, you can use json.parse() method to parse JSON:

var json = '{"result":true, "count":42}';
obj = JSON.parse(json);
StepUp
  • 36,391
  • 15
  • 88
  • 148