Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nice way to test if an object chain in JavaScript is valid [duplicate]

Tags:

javascript

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? :)

like image 473
David Avatar asked Nov 22 '16 15:11

David


1 Answers

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'));
like image 198
Nina Scholz Avatar answered Nov 09 '22 22:11

Nina Scholz