Created
June 26, 2018 18:17
-
-
Save jacobwyke/41948d9d1b620a836e6f80113274962b to your computer and use it in GitHub Desktop.
Question 1: As given
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 { | |
//take the first key in the object as it doesnt match the key | |
mixValue = mixValue[Object.keys(mixValue)[0]]; | |
} | |
} | |
return mixValue; | |
} | |
let objData = { | |
'a': { | |
'b': { | |
'c': 'd' | |
} | |
} | |
}; | |
//Returns 'd' | |
console.log(getNestedObjectValue(objData, 'a/b/c')); | |
console.log(getNestedObjectValue(objData, 'x/y/z')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment