Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@jpedroribeiro jpedroribeiro commented Jan 17, 2020

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
You can’t perform that action at this time.