DEV Community

Accessing Nested Objects in JavaScript

Dinesh Pandiyan on February 10, 2018

tldr; safely access nested objects in JavaScript in a super cool way. JavaScript is amazing, we all know that already. But a few things in JavaS...
Collapse
 
wesnetmo profile image
Wes
Collapse
 
wstone profile image
Will Stone

I have been looking forward to this a lot; checking the site on a near-weekly basis to see if it has progressed a stage

Collapse
 
flexdinesh profile image
Dinesh Pandiyan

It'll be great to see this operator soon in ES. I like the way how ES is progressing forward.

Collapse
 
martinhaeusler profile image
Martin Häusler

It's a GOOD thing that you get this error from JS! It tells you that something in your program and/or your data is wrong. By coding like this, you may circumvent the error message, but the root cause still exists. Use Typescript instead. It will tell you exactly when it is safe to navigate nested structures and when it is not. In the latter case, you should HANDLE the error, not ignore it.

Collapse
 
flexdinesh profile image
Dinesh Pandiyan

I agree TypeScript is safe and provides great many flexibilities in handling unexpected code.

But the alternate without a typescript (preference differs) would be to catch all these in a try catch block throughout the code, which will look really messy in a huge codebase. Sometimes, missing data in nested structures might be intentional too, mostly because JS is weakly typed. I think handling all those errors is a little too much effort and rather we should focusing on coding for the problem and let utils/libs handle the language shortcomings.

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.

Collapse
 
xngwng profile image
Xing Wang

or get from Lodash.

Collapse
 
flexdinesh profile image
Dinesh Pandiyan • Edited

Lodash is all too awesome and there's nothing you can't do in Lodash. I'm a big fan of it. But sometimes, in a few light-weight front-end codebases, I find Lodash to be heavy and prefer to write the util on my own, especially if I'll be needing only one or two methods from Lodash.

Collapse
 
skyrpex profile image
Cristian Pallarés

You can install any lodash method in isolation for that case. If you're bundling your assets, you can install lodash and load just the parts you need.

Collapse
 
jerolan profile image
Jerome Olvera

Lodash get all the things 🙌🙌🙌

Collapse
 
darrenvong profile image
Darren Vong

Some very nice solutions - I'm totally with you on writing your own util functions when it's small things, considering the impact from libraries like left-pad had when it was taken down! This will solve a lot of headache of nested property access until the optional/elvis operator becomes a thing in JS. Thanks for sharing!

Collapse
 
alexkli profile image
Alexander Klimetschek

Here is a simpler self-contained helper function:

function resolve(obj, path) {
    return path.split('.').reduce((o, key) => o && o[key], obj);
}

resolve(user, 'personalInfo.name');
resolve(user, 'personalInfo.addresses.0.city');

Note the dot notation, also works for arrays with index addressing.

Collapse
 
kepta profile image
Kushan Joshi

Instead of reinventing wheel, I highly suggest looking at lenses randycoulman.com/blog/2016/07/12/t...

Collapse
 
flexdinesh profile image
Dinesh Pandiyan

I am a big fan of Lodash and have heard a great deal about Ramda too. But most of the time I find myself working on a small project that doesn't need 99% of the utils in these libraries, especially on the front-end. In those cases, I prefer to either write the util on my own or use a micro library that works for my project. But anyway thanks for letting me know about lenses. This looks pretty interesting and I'm going to take a closer look at how it works internally.

Collapse
 
brownieboy profile image
Michael Brown

import _get from "lodash/get";

Collapse
 
vadirn profile image
Vadim K. • Edited

What about this?


function grab(fn, defaultValue) {
  try {
    const value =  fn();
    return value;
  } catch (err) {
    return defaultValue;
  }
}

// and then

const city = grab(() => user.personalInfo.address.city);

Collapse
 
vadirn profile image
Vadim K.

Ah, default value doesn't make sense here, so

function grab(accessor) {
 try {
   const value = accessor();
   return value;
 } catch(err) {
   return;
 }
}
Collapse
 
hrmny profile image
Leah

github.com/developit/dlv

How about something actually tiny?

Collapse
 
flexdinesh profile image
Dinesh Pandiyan

This is amazing. Concise and clean.

Do you want to be able to support arrays in string path? I can create a PR. But the code won't be as small though.

Collapse
 
zed_m profile image
Amine Hammou

thank you!

Collapse
 
lewismenelaws profile image
Lewis Menelaws

Too many times have I had >120 character variables of just trying to get nested objects. Very ugly. I am ashamed of myself.

Collapse
 
flexdinesh profile image
Dinesh Pandiyan

We've all been there. Cheers!

Collapse
 
elpibeperez profile image
Eduardo • Edited

Hey! Don't forget lodash.get! If you find loadash too heavy just import the get! I think is one of the most common ways of accessing nested objects until se get an Elvis operator like kotlin

Collapse
 
lucadv profile image
Luca Di Vincenzo • Edited

Or you could use lodash _.get(array[pos].property, defaultValue) and get a way cleaner code.