How is it more concise in JavaScript to return a value or undefined in a large object with nested objects?

  • 0
    For example, there is an object (this is for simplicity, in fact, it is huge and comes in a request)

    const obj = {
        obj1: {
            obj2: {
                key2: 22222222,
                obj3: {
                    key3: 321,
                    obj4: {
                        key4: 123
                    }
                }
            }
        }
    }
    
    const value1 = obj.obj1.obj2.obj3.obj4.key4;
    const value2 = obj.obj1.obj2.key2;
    
    console.log(value1)
    console.log(value2)

    The bottom line is that obj can come with obj4, but maybe not, if it is not there then there will be an error like "Cannot read property 'key4' of undefined". Likewise, if there is no higher level.
    What is the more concise and correct way to return the value of either undefined value1 or value2, using as little as possible checking the chain of nested objects? If there are ways?
    JavaScript Anonymous, Dec 6, 2019

  • 1 Answers
  • 0
    You can take advantage of the new - Optional Chaining:

    https://developer.mozilla.org/en-US / docs / Web / JavaS ...



    In any other case, you have to do the checks manually:

    `if (obj & amp; & amp; obj.key1 & amp; & amp; obj.key1.key2 ...`
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!