Skip to content

Instantly share code, notes, and snippets.

@jacobwyke
Created June 26, 2018 18:22
Show Gist options
  • Save jacobwyke/9e86f61ccb844a7c2f6ffb818e8d0b3c to your computer and use it in GitHub Desktop.
Save jacobwyke/9e86f61ccb844a7c2f6ffb818e8d0b3c to your computer and use it in GitHub Desktop.
Question 1 Alternate
function getNestedObjectValue(objObject, strKey) {
//split the key into parts
let arrParts = strKey.split('/');
//get array length before loop for optimisation
let numLength = arrParts.length;
//create variable to hold object position
let mixValue = objObject;
//loop through parts
for (let numX = 0; numX < numLength; numX++) {
let strKey = arrParts[numX];
//ensure that key exists
if (mixValue.hasOwnProperty(strKey)) {
//store the new value
mixValue = mixValue[strKey];
} else {
throw "Key '" + strKey + "' not found.";
}
}
return mixValue;
}
let objData = {
'a': {
'b': {
'c': 'd'
}
}
};
let objData2 = {
'x': {
'y': {
'z': 'd'
}
}
};
//Returns 'd'
console.log(getNestedObjectValue(objData, 'a/b/c'));
//Returns 'd'
console.log(getNestedObjectValue(objData2, 'x/y/z'));
//Throws exception
console.log(getNestedObjectValue(objData, 'a/b/x'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment