0

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

user1hjgjhgjhggjhg
  • 1,137
  • 3
  • 13
  • 29

2 Answers2

4

The syntax you're looking for is cities[city]. As is, your code is looking for a property of cities literally called 'city'

jmcgriz
  • 2,731
  • 1
  • 8
  • 10
0

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.

Kamalakannan J
  • 2,639
  • 3
  • 20
  • 46