When calling an authentication API, I receive an Observable<any>
with the following object:
name: "John"
role: "Admin"
The response may vary in a few ways:
Extra fields could be included;
If a field has multiple values, it is returned as an array:
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4dedbdcdaf4d1ccd5d9c4d8d19ad7dbd9">[email protected]</a>" // 1. Extra Field name: "John" role: ["Admin", "Editor"] // 2. Field now contains 2 values
To handle this, I've created an interface:
export class Claim {
type: string;
value: string;
}
I need to create an array of Claims based on the object received.
For the first example, the array of Claims would be:
type value
name John
role Admin
And for the second example:
type value
email <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e444146406e4b564f435e424b004d4143">[email protected]</a>
name John
role Admin
role Tutor // Multiple claims of same type
Update:
Based on pc_coder's answer, my code looks like this:
getClaims(type: string): Observable<Claim[]> {
return this.getUser().pipe(map(user => {
let claims: Claim[] = [];
Object.entries(user.profile).forEach((element)=>{
if (typeof element[1] == "object") {
element[1].forEach(x => {
claims.push({ type: element[0], value: x })
})
}
else {
claims.push({ type: element[0], value: element[1]})
}
});
return claims;
}));
}
Can I use RXJS operators to improve the transformation process? Also, is it possible to filter claims by type when the type
parameter of getClaims
is provided?