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

Spirally Traversing a Two-Dimensional Array in JavaScript

This is a way to traverse a two-dimensional array (or a matrix) from the top left, spirally in a clockwise manner in JavaScript. This solution is inspired by functional programming and it uses tail recursion. Steps: When you start with... Continue →