Is there any safe way to check the deep of object's property?

alramdein
const object = {
    level1: {
      level2: {
        level3: 'foo'
      }
    }
  }

Let's say I want to get level3's value

console.log(object.level1.level2.level3);

That's so risky considering level1 and level2 could be null or undefined. Is there any simple way to get level3 value safely? Beside check the object properties one by one like this

if (object.level1) {
    if (object.level2) {
      if (object.level3) {
        // do stuff
      }
    }
  }
Ran Turner

That is exactly why you have Optional chaining (introduced in ES2020) in javascript.

It's an operator (?.) which enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is null/undefined so it actually protects you from getting a null reference error.

console.log(object.level1?.level2?.level3);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Safe way to check if a property of an object contains a substring

How to check for deep object property

Check if any property in a object is empty

Object has-property-deep check in JavaScript

Any way to find deep string in a object?

Is there any way to check an inherited CSS property in protractor?

check if any property in an object is nil - Swift 3

Check if any object property contains string

Is this a safe way to check if a property exist else assign one?

What is the correct way to check object's property if object not undefined in angular 2 template?

How to check in neat way if collection contains an object which's one property is equal to the object passed to Contains method?

is there any way to get the object from its property?

Correct way to check if any object is a SyntheticEvent?

Is there any way to check if an object is a type of enum in TypeScript?

In scala, is there any way to check if an instance is a singleton object or not?

Is there any way to check whether an object is serializable or not in java?

ES6 Check property value in deep nested dynamic object

Typescript check if property in object in typesafe way

Safe way to get a string representation of any JavaScript value or object

Any way to assign a variable (not an object property) another variable's value by reference in JavaScript?

Any way to enforce a property's type in a CFC?

Better way to check Nullability of deep level Object reference?

Is there any way to check a cookie's origins

Any way to check an object if its breeze entity object?

JavaScript - check if object's property is an array

swift check an object's property existence

Check if an Item's Property's value matches any from a list

Check if an attached object have any related data base on navigation property

How to check any every array object property empty or not?