Considering this example:
    if(this.plantService.plants[id])
    {
        if(this.plantService.plants[id].Name)
        {
            if(this.plantService.plants[id].Name[0])
                return this.plantService.plants[id].Name[0].value;
            else
                return '';
        }
        else
            return '';        
    }    
    return '';
I am wondering if it is possible to simplify what I am doing here.
My goal is to test the object-chain this.plantService.plants[id].Name[0] for validity. 
However, if I just test if(this.plantService.plants[id].Name[0]) {...} exceptions are thrown. 
Any proposals? :)
You could reduce the array with the object, after checking value and type.
function getIn(object, keys, def)  {
    return keys.reduce(function (o, k) {
        return o && typeof o === 'object' && k in o ? o[k] : def;
    }, object);
}
var object = { plantService: { plants: [{ Name: [{ value: 42 }] }] } };
console.log(getIn(object, ['plantService', 'plants', 0, 'Name', 0, 'value'], 'default value'));
console.log(getIn(object, ['b', 'c', 'd', 'e'], 'default value'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With