J. Pedro Ribeiro

Getting a nested property of an object with dot notation

January 18, 2020

Let’s say you have a JSON file with your data. You parse it into an object literal:

  const myObject = {
    foo: {
      bar: {
        baz: 123
      },
      ...
      xyz: "test"
    }
  };

Your app (maybe your CMS, or an i18n library) asks for the content of a specific path:

const myPath = "foo.bar.baz";

How would you get the value of this property?

This is what I came up with:

function getPropValue(sourceObject, dotNotationPath) {
  let returnData = sourceObject;

  dotNotationPath.split(".").forEach(subPath => {
    returnData = returnData[subPath] || `Property ${subPath} not found`;
  });

  return returnData;
}

Basically, I’m breaking down the path string into an array (split), looping through each property. As I go to each property, returnData receives the nested object of that specific level, up until we reach the final property, which will be the value we want.

console.log(getPropValue(myObject, myPath)); // 123

If the path doesn’t exist or a property down the road is not present, you get the error message:

const myPath2 = "foo.zoo"
console.log(getPropValue(myObject, myPath2)); // "Property zoo not found"

J. Pedro Ribeiro

Hello!
I’m a Brazilian front-end developer living in London. This website features some of my latest projects and my thoughts on anything web related.
You can find me on Twitter, Instagram, and LinkedIn.