Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 shorthand object key checking

Curious to know if there's any part of ES6 that makes these kind of checks a little more concise:

componentWillReceiveProps(nextProps) {
    if(nextProps && nextProps.filterObj && nextProps.filterObj.area){
        // go ahead
    }
}
like image 844
benhowdle89 Avatar asked May 22 '15 11:05

benhowdle89


People also ask

How do I check if an object contains a key?

You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain. Note: The value before the in keyword should be of type string or symbol .

How do you check if an object is inside an object?

The first way is to invoke object. hasOwnProperty(propName) . The method returns true if the propName exists inside object , and false otherwise. hasOwnProperty() searches only within the own properties of the object.

How do I check if an object is nested?

We can write our own JavaScript function to check if a deeply nested property exists in an object. };console. log(checkNested(obj, 'level1', 'level2', 'level3')); console.

How do you check if a key is present in an array of objects JavaScript?

Using hasOwnProperty() function The function hasOwnProperty() will check for the existence of a key in the given object and returns true if the key is present or else it returns false. This function takes the key of the object as the parameter and returns the Boolean result accordingly.


1 Answers

No, no existential operator has made it into ES6; it is still discussed however.

You can use any of the existing methods, of course, like

if ( ((nextProps||{}).filterObj||{}).area ) {
    // go ahead
}

Also you can try destructuring and default values:

function componentWillReceiveProps({filterObj: {area} = {}} = {}) {
    if (area) {
        // go ahead
    }
}
like image 106
Bergi Avatar answered Oct 19 '22 03:10

Bergi