-1

I have something like that:

add(messenger) {
  switch (messenger) {
    case 'skype':
      this.messengers = _.assign(this.messengers, {skype: ''})
      break
    case 'telegram':
       this.messengers = _.assign(this.messengers, {telegram: ''})
       break
  }
}

But are there ways to make it shorter? Like this:

add(messenger) {
  this.messengers = _.assign(this.messengers, {messenger: ''})
},
  • 1
    Use bracket notation: `_.assign(this.messengers, {[messenger]: ''})`. – CRice Sep 13 '18 at 20:22
  • Is there no good dupe target for computed properties? – Luca Kiebel Sep 13 '18 at 20:23
  • 1
    Maybe: Possible duplicate of [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – CRice Sep 13 '18 at 20:24

2 Answers2

1

using ES6, you can do this.

add(messenger) {
    this.messengers = _.assign(this.messengers, { [messenger]: '' });
}
oosniss
  • 440
  • 1
  • 7
  • 14
0

Yup, you can set a key to a variable value using square brackets, like so:

this.messengers = _.assign(this.messengers, {[messenger]: ''})
Steve Archer
  • 641
  • 4
  • 10