0

Given the following path, I want to return "name" if possible or "" otherwise:

countries[0].states[0].cities[0].name

One option is to check step by step:

if(countries && countries[0]){
    var states = countries[0].states;
    if(states && states[0]){
        var cities = states[0].cities;
        if(cities && cities[0]){
            var name = cities[0].name;
            if(name){
               return name;
            }
        }
    }
}
return "";

Which is verbose. Another option is exception handling:

try {
   var name = countries[0].states[0].cities[0].name;
   return name ? name : ""; // handle null or undefined
} catch(err) {
   return "";
}

But we may be uncomfortable to involve exception handling on plain logic and it also costs performance.

Is there another short/clean way to do it?

Victor Basso
  • 5,556
  • 5
  • 42
  • 60

2 Answers2

2

You can build a helper to do it:

function readProperties(object, path) {
    return path.reduce(function (object, key) {
        return object && object[key];
    }, object);
}
…
return readProperties(countries, [0, 'states', 0, 'cities', 0, 'name']) || '';
Ry-
  • 218,210
  • 55
  • 464
  • 476
1

If you use lodash.js or underscore, you could do:

    if (_.get(countries, '[0].states[0].cities[0].name')) {

    }   
abel leroyer
  • 285
  • 2
  • 8