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

Adapter Pattern in JavaScript

The adapter pattern is a concept where two incompatible interfaces are made to work together using the adapter. The adapter is useful for when changing frameworks in large complex projects. Say you started development using Backbone... Continue →