Get the nested object in an object literal

This is a way in JavaScript to get a deeply nested object in an object literal. This is especially useful when we are unsure about the data we are receiving. This allows our code to be able to handle one or more instances of data received. So if the optional data is in the object literal, then we can use it if not it won’t break the code nor will it add unnecessary try-catch blocks or if-else clauses to the codebase.

var test = { first:{second:{third:'found it!'}} };

Object.prototype.get = function(path) {
    var arr = path.split('.');
    var obj = this;
    for(var i = 0; i < arr.length; i++) {
        var e = arr[i];
        if(obj[e] === undefined) {
            obj[e] = {};
        }
        obj = obj[e];
    }
    return obj;
}

test.get('first.second.third') == 'found it!'; // true

We are able to use the method get in any object literal as we added it to Object’s prototype which is a feature in the JavaScript language.

 
3
Kudos
 
3
Kudos

Now read this

React Rally 2016 Recap

I recently attended the React Rally conference in Salt Lake City, UT. The conference was about the front end server and client framework React, created by Facebook. Speakers covered topics such as Redux, Relay, RethinkDB, Async and of... Continue →