Skip to content

Instantly share code, notes, and snippets.

@saintsGrad15
Created April 14, 2017 20:03
Show Gist options
  • Save saintsGrad15/66e5902110a4f91a65b6e6d4d864abb6 to your computer and use it in GitHub Desktop.
Save saintsGrad15/66e5902110a4f91a65b6e6d4d864abb6 to your computer and use it in GitHub Desktop.
A function to retrieve the value inside an object at a dot-delimited path.
function getObjectValueFromDottedNotation(object, dottedString)
{
/*
* Given an object 'object' and a string 'dottedString' that contains a dot-delimited path
* down the object's members, return the value at that path or false if the entire path does not exist.
*
* For example:
* obj = {
* "person": {
* "name": "john",
* "family": {
* "mom": "Mary Ann",
* "dad": "David"
* }
* }
* }
*
* getObjectValueFromDottedNotation(obj, "person.family.mom") == "Mary Ann";
*
* :param: object: A Javascript object.
*
* :param: dottedString: A dot-delimited string expressing a path down 'object's members.
*
* :return: The value inside of 'object' at 'dottedString' or false if no such path exists.
*/
let keys = dottedString.split(".");
let currentLevel = object;
for (key of keys)
{
if (typeof currentLevel !== "undefined")
currentLevel = currentLevel[key];
}
if (typeof currentLevel === "undefined")
return false;
return currentLevel;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment