DEV Community

Discussion on: Accessing Nested Objects in JavaScript

Collapse
 
itachiuchiha profile image
Itachi Uchiha

I use extract method for my project. Purpose can be different. These codes from my localization project on Github.

github.com/aligoren/local.js/blob/...

 extract(propertyName, object) {
        const parts = propertyName.split(".");
        let length = parts.length;
        let i;
        let property = object || this;

        for (i = 0; i < length; i++) {
            property = property[parts[i]];
        }

        return property;
    }

Usage:

const locals = {
    "tr": {
        "btn": {
            "welcome": {
                "text": "Merhaba hoşgeldin"
            },
            "other": "Diğeri"
        }
    },
    "en": {
        "btn": {
            "welcome": {
                "text": "Hi Welcome"
            },
            "other": "Other"
        }
    }
}

this.extract('btn.welcome.text', locals['tr'])
Collapse
 
flexdinesh profile image
Dinesh Pandiyan • Edited

This is great and easily readable. Maybe we should benchmark all the ways to access nested objects and spread the word so the community will know which one to use and when.

Collapse
 
carlosnufe profile image
Carlos Núñez

Take a look at i18n library, works in this way.