Reputation: 31
Given an object I want to get the properties that match an specified condition on if statement. Is it possible?
object = {...};
if(object.privativa > 0 || object.comunitaria > 0 ||
object.antiocupa > 0 || object.trastero > 0 || object.cancela > 0 ||
object.parking > 0 || object.mando > 0 || object.otros > 0 ||
object.otros2 > 0 || object.otros3 > 0) {
**FIRST PROPERTY MATCHED HERE**
}
Thanks in advance.
Upvotes: 0
Views: 132
Reputation: 780851
You could do it by putting comma expressions in the if
:
let prop;
if ((prop = 'privativa', object[prop] > 0) ||
(prop = 'comunitaria', object[prop] > 0) ||
(prop = 'antiocupa', object[prop] > 0) ||
...
) {
// prop contains the first matched property
}
This takes advantage of the short-circuiting of the ||
operator. It stops evaluating expressions when it gets the first truthy one. And the comma operator evaluates its two operands and returns the value of the second one.
While this answers the question, I don't actually recommend writing code like this. It's likely to be confusing to readers of the code, and looping through an array or using .find()
as in Mark Meyer's answer would be preferable. Learning things like this is useful for Code Golf competitions, but not for real programming, where clarity is important.
Upvotes: 0
Reputation: 92440
Instead of a bunch of ||
conditions, you might be better off with an array of property names in the order you want to search. Then you can use array.find()
to get the first one that matches a condition like > 0
:
// some object
let object = {
privativa: 0,
comunitaria: -2,
antiocupa: 0,
trastero: 0,
cancela :1,
parking:0,
otros: 1,
otros2: 0,
otros3: 1
}
// keys in the order you want to search
let keys = ['privativa', 'comunitaria', 'antiocupa', 'trastero', 'cancela','parking' ,'otros' ,'otros', 'otros3']
// find the first that matches you condition
let k = keys.find(k => object[k] > 0)
console.log("property:", k, "value:", object[k])
// You can also get ALL the keys that match and pick the first one.
let ks = keys.filter(k => object[k] > 0)
console.log("All matching keys: ", ks)
Upvotes: 1