Reputation: 1327
I have a question similar to this question and has a slightly different problem.
So I have a function in cities.js
file
module.exports = {
newyork: function (latitude,longitude) {
console.log("newyork is here");
}
If I access this function this way if(cities.newyork){}
then true and false condition works fine but If I access function this way
var city = 'newyork';
if(cities.city){
console.log("true");
}else{
console.log(false);
}
It always goes in else condition. Because cities names would be dynamic so I need this function to work. I have tried this way as well
if(typeof cities.city === 'function'){
console.log("true");
}else{
console.log(false);
}
Still no luck. Any help would be appreciated
Upvotes: 0
Views: 1262
Reputation: 2998
You should use, cities[city]
. This is because,
In cities.city
, "city" will be considered as "key name". So it will transformed as cities["city"]
But in cities[city]
it will actually transform to cities["newyork"]
So always use, obj[dynamic_key_name]
. Access property with "."
only when you know the property name.
Upvotes: 0
Reputation: 3358
The syntax you're looking for is cities[city]
. As is, your code is looking for a property of cities literally called 'city'
Upvotes: 4