Skip to content

Instantly share code, notes, and snippets.

@jpedroribeiro
Last active June 12, 2023 09:48
Show Gist options
  • Save jpedroribeiro/8950ed3f10e505cadb7f62467714ab98 to your computer and use it in GitHub Desktop.
Save jpedroribeiro/8950ed3f10e505cadb7f62467714ab98 to your computer and use it in GitHub Desktop.
How to get a nested property of an object with dot notation
/*
* Returns the value of a property in a nested object.
*
* @param {Object} sourceObject
* @param {string} dotNotationPath
* @returns {*}
*
*/
function getPropValue(sourceObject, dotNotationPath) {
let returnData = sourceObject;
dotNotationPath.split(".").forEach(subPath => {
returnData = returnData[subPath] || `Property ${subPath} not found`;
});
return returnData;
}
@jpedroribeiro
Copy link
Author

Usage example:

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

const myPath = "foo.bar.baz";
const mySecondPath = "foo.xyz";

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment