Skip to content

Instantly share code, notes, and snippets.

@jacobwyke
Created June 26, 2018 18:17
Show Gist options
  • Save jacobwyke/41948d9d1b620a836e6f80113274962b to your computer and use it in GitHub Desktop.
Save jacobwyke/41948d9d1b620a836e6f80113274962b to your computer and use it in GitHub Desktop.
Question 1: As given
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