Unable to use local variable in a return

Hi, I am using Angular and Typescript for my project, I have a problem with the return of a variable name, it doesn’t like it, Please help?

packageClasses(thispackage: Package) {
    this.selectedPackage = thispackage;
    this.packageName = this.selectedPackage.name.toLowerCase().replace(/\s+/g, '-');
    this.packageName = this.packageName.replace(/[!@#$%^&*]/g, '');
    return {
      this.packageName: true
    };
  }

That isn’t valid syntax: you’re returning an object, and object keys have to be actual strings (or integers or symbols) in JavaScript, you can’t use variables like that. You need to evaluate the variable to a string using computed properties like so:

return {
  [this.packageName]: true
};

Which will evaluate this.packageName to the string you want it to be. You can use computed properties every time you need to dynamically create an object key, they’re very useful – here’s a concise overview, they’re very simple to use.

Just for comparison, if you weren’t using them, then you’d need to do:

packageClasses(thispackage: Package) {
  this.selectedPackage = thispackage;
  this.packageName = this.selectedPackage.name.toLowerCase().replace(/\s+/g, '-');
  this.packageName = this.packageName.replace(/[!@#$%^&*]/g, '');
  
  const example = {}
  example[this.packageName] = true;
  return example;
}

But using computed properties is much simpler and clearer.

2 Likes