Hey guys !
I would need your help here, I have 3 booleans associated with values, let’s say:
* Blue Car: true/false
* Red Car: true/false
* Black Car: true/false
Based on the boolean value (true = present), the output object should be:
params = ['BLUE_CAR','RED_CAR','BLACK_CAR']
For instance:
* Blue Car: false
* Red Car: true
* Black Car: true
params = ['RED_CAR','BLACK_CAR']
I was thinking about multiple ifs…but it doesn’t feel elegant.
Do you have a better idea ?
ilenia
November 7, 2020, 8:20am
2
a filter method?
a loop?
thebest way depends in how you get the values
Thanks @ilenia for your response.
Well, that’s the issue I guess. The booleans are stored in this format:
* properties.bluecar
* properties.redcar
* properties.blackcar
ilenia
November 7, 2020, 8:24am
4
so why not a for…in over the object?
for (let car in properties) {
if (properties[car]) {
...
}
}
I understand that the proposed code matches all variables with a car
suffix in properties
object and loop over these values, right ?
ilenia
November 7, 2020, 8:29am
6
a for…in loop loops over all the properties
Yes.
Apologies, I have not seen specific enough, actually properties
contains much more (which I don’t want in the output object) than only the car colors, , that’s why it makes value retrieval more challenging I guess.
ilenia
November 7, 2020, 8:51am
8
for (let car of ["bluecar", "redcar", "blackcar"]) {
if (properties[car]) {
...
}
}
The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with...
jenovs
November 7, 2020, 9:02am
9
Quick and dirty:
const params = []
properties.bluecar && params.push('BLUE_CAR')
properties.redcar && params.push('RED_CAR')
properties.blackcar && params.push('BLACK_CAR')