Created
June 26, 2018 18:22
-
-
Save jacobwyke/9e86f61ccb844a7c2f6ffb818e8d0b3c to your computer and use it in GitHub Desktop.
Question 1 Alternate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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