简体   繁体   中英

How to handle both a single item and an array of string type in javascript / typescript

I get response from an api regarding user roles, if user has one role, I get single value place holder ie

    {
  "nameid": "1",
  "unique_name": "Anees",
  "role": "Student",
  "nbf": 1587681052,
  "exp": 1587767452,
  "iat": 1587681052
}

If user has more than one roles, roles consider as array ie.

    {
  "nameid": "2",
  "unique_name": "Naveed",
  "role": [
    "SuperAdmin",
    "Admin",
    "Teacher",
    "Clerk",
    "Student"
  ],
  "nbf": 1587712850,
  "exp": 1587799250,
  "iat": 1587712850
}

How can I handle both a single value and a collection in same place holder?

This script work fit for me

const userRoles = this.decodedToken.role as Array<string>;

I have to use some collection methods like find etc

var status = userRoles.find(x => x == role);

it gives error in case of single value.

Any solution, please.

You could convert the single item to an array containing single element. Check if the element is an array using Array.isArray() function. Try the following

const userRoles = Array.isArray(this.decodedToken.role) ? this.decodedToken.role : [this.decodedToken.role];

let status = userRoles.find(x => x == role);

As a sidenote, using let instead of var helps to keep things the Typescript way.

Casting will always succeed, so you need to check the type at runtime.

You can check to see if the value is an array using isArray

const isRolesArray = Array.isArray(userRoles)

var status = isRolesArray ? userRoles.find(x => x == role) : userRoles === role;

Or you can cast to the proper typescript type using union types and do a check using type guards . So you can do something like this

const userRoles = this.decodedToken.role as Array<string> | string;

let status

if (typeof userRoles === "string") {
 status = userRoles === role
} else {
 status = userRoles.find(x => x == role);
}

This way you get all the typechecking goodness from Typescript.

you can use something like this. Array.isArray() can easily check this

//declares a variable for object

let newobject = {
 "nameid": "2",
 "unique_name": "Naveed",
 "role": [
 "SuperAdmin",
 "Admin",
 "Teacher",
 "Clerk",
 "Student"
 ],
"nbf": 1587712850,
"exp": 1587799250,
"iat": 1587712850
}
function t(arr){
 let status;
 if(Array.isArray(arr)){
  status = arr.find(x => x == "Admin");
 } else {
  status = newobject.role;
 }
console.log('status ',status);
}
t(newobject.role); //call this for activating the check

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM