Reputation: 361
I have a method getPreferredfood(). It gets three boolean values that represent different food items. Which ever of them are true, you return those.
getPreferredFood: function (){
var item 1;
var item2 ;
var item3;
//comparison?
return "Preferred food is " (whichever item was true)
}
I'm not sure how to return the the item that are true.
Upvotes: 1
Views: 1609
Reputation: 93461
I recommend to attach your variable to namespace (example: api
) :
var api={};
api.vegan= true
api.non_veg= false
api.veg = false;
Then , what you need is to loop through properties of this namespace and filter true ones .
'Person prefers '+Object.keys(api).filter((ky)=>api[ky]).join(',');
If you cannot add it to namespace ,the default namespace is window
& you need then to have a whitelist to loop on .
var api={};
api.vegan= true;
api.non_veg= false;
api.veg = false;
console.log(
'Person prefers '+ Object.keys(api).filter((ky)=>api[ky]).join(',')
)
Upvotes: 0
Reputation: 4785
var preferenceValues = {
'vegan': true,
'non-veg': false,
'veg': false
}
function getPreferences(preferenceValues) {
var preferences = [];
for(type in preferenceValues) {
if (preferenceValues[type]) {
preferences.push(type);
}
}
return 'Person prefers ' + preferences.join(', ') + ' food';
}
console.log(getPreferences(preferenceValues))
Upvotes: 1
Reputation: 57703
It looks like you want to use the variable name as part of a string output. That's not usually how you want to do things.
Consider doing this instead:
var tags = {
"vegan": true,
"non-veg": false,
"veg": false
};
var true_tags = [];
for (var tag in tags) {
if (tags[tag] === true) {
true_tags.push(tag);
}
}
console.log(true_tags); // will print [ "vegan" ]
Upvotes: 2
Reputation: 816960
Store the values in an object / map:
var options = {
a: true,
b: true,
c: false,
};
Use Object.keys
to get the names and use .filter
on that array to filter out the ones that are false
:
Object.keys(options).filter(function(x) {
return options[x];
});
// ['a', 'b']
Upvotes: 3