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?

4 Answers 4

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)) {
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

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.

1 Comment

Or use ['...', '...'].includes(str) with ES2016.
0

A lodash way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.