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

ES7 Async Await in JavaScript

This is a blog post on the async and await functionality coming to JavaScript. It is currently on Stage 3 Draft but is well adopted in tools such as Babel which transpiles the code into Generators (which is actually transpiled again by... Continue →