Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ourmaninamsterdam/50f9e1f48c2ac80b3ef8 to your computer and use it in GitHub Desktop.
Save ourmaninamsterdam/50f9e1f48c2ac80b3ef8 to your computer and use it in GitHub Desktop.
A Pen by Justin Perry.
var obj = {
key1 : 'key1Value1',
key2 : {
subKey1 : 'subKey4Value1',
subKey2 : 'subKey2Value2',
subKey3 : 'subKey3Value3',
subKey4 : 'subKey4Value4'
},
key3 : {
subKey1 : {
subSubKey1 : 'subSubKeyValue1',
subSubKey2 : 'subSubKeyValue2',
subSubKey3 : 'subSubKeyValue3',
subSubKey4 : 'subSubKeyValue4'
}
},
key4 : {
subKey1 : {
subSubKey1 : {
subSubSubKey1 : 'subSubSubKeyValue1'
}
}
}
};
function get(keys){
keys = keys.split('.');
var _from = function(obj) {
var context = obj;
for(var i = 0; i < keys.length;i++) {
if(context.hasOwnProperty(keys[i])) {
context = context[keys[i]];
}
else {
return undefined;
}
}
return context;
};
return {
from : _from
};
}
console.log(get('key1').from(obj) ); // key1Value1
console.log(get('key2').from(obj) ); // Object {subKey1: "key6subkeyvalue1", subKey2: "key6subkeyvalue2", subKey3: "value3", subKey4: "value4"}
console.log(get('key3.subKey1').from(obj) ); // Object {subSubKey1: "subSubKeyValue1", subSubKey2: "subSubKeyValue2", subSubKey3: "subSubKeyValue3", subSubKey4: "subSubKeyValue4"
console.log(get('key3.subKey1.subSubKey1').from(obj) ); // subSubKeyValue1
console.log(get('key4.subKey1.subSubKey1.subSubSubKey1').from(obj) ); // subSubSubKeyValue1
console.log(get('something.that.is.not.there').from(obj) ); // undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment