简体   繁体   中英

Alter value in object

Writing Javascript, I have an object/class with the following attributes:

this.option1Active = null;
this.option2Active = null;
this.option3Active = null;
this.option4Active = null;

I would like to set one of those attributes to true based on the parameter genre

function selectGenre (genre) {
  if (genre === 'option1') {
    this.option1Active = true;
  }

  else if (genre === 'option2') {
    this.option2Active = true;
  }

  else if (genre === 'option3') {
    this.option3Active = true;
  }

  else if (genre === 'option4') {
    this.option4Active = true;
  }
}

Though writing if statements is not a sustainable solution. I'd like to do something like this:

function selectGenre (genre) {
  var options = {
    'option1': this.option1Active,
    'option2': this.option2Active,
    'option3': this.option3Active,
    'option4': this.option4Active
  };

  options[genre] = true;
}

But that only set options[index] to true, not eg this.option1Active . Is there a way to change the reference a key of an object points to?

If not, other ways of refactoring the if statements is greatly appreciated.

You can use a string for the property name to set on this .

var genreOptions = {
  'option1': 'option1Active',
  'option2': 'option2Active',
  'option3': 'option3Active',
  'option4': 'option4Active'
};

function selectGenre (genre) {
  this[genreOptions[genre]] = true;
}

It seems you can just append "Active" to genre to get the property itself:

function selectGenre (genre) 
{
  var prop = genre + 'Active';

  if (typeof this[prop] != 'undefined') {
      this[prop] = true;
  }
}

Though, it would be easier if you could use an array as your property instead, ie this.optionActive[3] vs. this.option3Active .

Is this what you want ?

var obj = {};
obj.option1Active = null;
obj.option2Active = null;
obj.option3Active = null;
obj.option4Active = null;

var options = {
    option1: 'option1Active',
    option2: 'option2Active',
    option3: 'option3Active',
    option4: 'option4Active'
};

function selectGenre(genre) {
    obj[options[genre]] = true;
}

console.log(obj);
selectGenre('option2');
console.log(obj);

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