简体   繁体   中英

Access object property with variable and fallback to default property if non-existing

I'm new to the switch statement in Javascript. The cool thing about it is that it combines multiple if statements with a default result if all if's failed.

I'm a curious person and would like to know how this "default" if all else failed could be achieved with the object property select with a variable.

Example:

const action.type = "non-existing-property";

const runF = {
  CREATE_PROJECT_SUCCESS: () => {
    console.log("created project");
    return state;
  },
  CREATE_PROJECT_ERROR: () => {
    console.log("create project error");
    return state;
  },
  default: ()=>{
    console.log("Do default stuff if all else failed");
    return state;
  }
}[action.type];
runF();

Usually the action.type value would either be CREATE_PROJECT_SUCCESS or CREATE_PROJECT_ERROR. But what happens if the property is not existing? Then I would like to run the default property.

Anyone has an idea how this could be done?


Update:

I found one possible solution, but this requires another if statement. I would like to see a more smaller, quick solution. const action.type = "non-existing-property";

let runF = {
  CREATE_PROJECT_SUCCESS: () => {
    console.log("created project");
    return state;
  },
  CREATE_PROJECT_ERROR: () => {
    console.log("create project error");
    return state;
  }
}[action.type];

if (!runF) {
  //runF not defined/valid -> run default function
  runF = () => {
    console.log("Do default stuff if all else failed");
    return state;
  };
}

runF();

You can use logical OR operator ( || ) inside property accessor to implement fallback to default property name. Something like this:

const runF = {
  CREATE_PROJECT_SUCCESS: () => {
    console.log("created project");
    return state;
  },
  CREATE_PROJECT_ERROR: () => {
    console.log("create project error");
    return state;
  },
  default: ()=>{
    console.log("Do default stuff if all else failed");
    return state;
  }
}[action.type || 'default'];
runF();

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