1

I look for a solution to check if the value of the labelKey property is to_be_rented or to_be_put_on_sale

With a condition we can do it with :

if (this.project.currentProduct.productStatus.labelKey === ('to_be_rented' || 'to_be_put_on_sale')) {

}

But it does not work, and I also look for a more sophisticated alternative using Lodash or es2015 for example.

How can I do that?

sergdenisov
  • 8,327
  • 9
  • 48
  • 63
Mouad Ennaciri
  • 1,217
  • 3
  • 15
  • 28

4 Answers4

2

Your condition works so:

  1. The result of the expression to_be_rented || to_be_put_on_sale is to_be_rented always.
  2. You compare that labelKey equals to to_be_rented.

The correct solution is to compare labelKey with both strings:

let labelKey = this.project.currentProduct.productStatus.labelKey;
if (labelKey === 'to_be_rented' || labelKey === 'to_be_put_on_sale')) {
   ...
}

With ES2016 it can be simplified:

let values = ['to_be_rented', 'to_be_put_on_sale'];
if (values.includes(this.project.currentProduct.productStatus.labelKey)) {
  ...
}
alexmac
  • 19,087
  • 7
  • 58
  • 69
1

You can put all your variants in an array and use Array.prototype.indexOf() (it's even in ES5):

const variants = ['to_be_rented', 'to_be_put_on_sale'];
const labelKey = this.project.currentProduct.productStatus.labelKey;
if (variants.indexOf(labelKey) !== -1) {
  ...
}

Or Array.prototype.includes() (it's in ES2016):

if (variants.includes(labelKey)) {
  ...
}

These ways are more convenient when you have more than 2 variants.

For your case Array.prototype.indexOf() and Array.prototype.includes() will be the same, but the difference between these functions you can check out here.

sergdenisov
  • 8,327
  • 9
  • 48
  • 63
1

You could use an array and Array#includes for a check if the value exist in the array.

const values = ['to_be_rented', 'to_be_put_on_sale'];
if (values.includes(this.project.currentProduct.productStatus.labelKey)) {
    // do something
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

A lodash way:

var toFind = this.project.currentProduct.productStatus.labelKey;
if(_.find(['to_be_rented', 'to_be_put_on_sale'], toFind)) {
  // do something
}
Yong Li
  • 607
  • 3
  • 15