javascript – Checking the non-emptiness of an object property

Question:

For example, there is an object:

var obj = {
   param: {
      param2: 12 
   }
}

I want to add a unit to param2 , that is, obj.param.param2++ . But you can't write this way: there may be an error, so I need to check:

if (obj && obj.param && obj.param.param2 && obj.param.param2 > 0)

Question.
How can one easily and elegantly check obj.param.param2 without checking the whole chain?

As an example, in PHP you can use the is_empty($var['param']) function. It will return true if there is any problem with $var['param'] , and it doesn't matter if it exists or is just empty.

Answer:

You need to go through the properties branch one by one and create the properties that are missing along the way. I would make a method to pass the property chain as a string, and it would create whatever it needs and increment the property:

obj.plusplus('param.param2'); // obj.param.param2++

The method is something like this ( fiddle ):

var plusplus = function() {
    var args = arguments[0].split('.'), C = this, i;

    for( i = 0; i<args.length; i++) {
        if( !C.hasOwnProperty( args[i])) {
            C[ args[i]] = (i == args.length-1) ? 0 : {};
        }

        if( i == args.length-1) {
            C[ args[i]]++;
            return C[ args[i]];
        }
        C = C[ args[i]];
    }
}
Scroll to Top