Skip to content

Instantly share code, notes, and snippets.

@Drevanoorschot
Last active May 12, 2020 21:10
Show Gist options
  • Save Drevanoorschot/0d397ba5a3f376d8ae8d6c51dd9f9240 to your computer and use it in GitHub Desktop.
Save Drevanoorschot/0d397ba5a3f376d8ae8d6c51dd9f9240 to your computer and use it in GitHub Desktop.
/*
{
"a":{
"b":{
"b1":1
},
"c":2
}
}
*/
const dummy_object_complete = JSON.parse("{\"a\":{\"b\":{\"b1\": 1}, \"c\": 2}}");
/*
{
"a":{
"c":2
}
}
*/
const dummy_object_incomplete = JSON.parse("{\"a\":{\"c\": 2}}");
const DELIMETER = "."
class UniversalObject {
constructor(object) {
this.elements = new Object();
for (let key in object) {
if (object.hasOwnProperty(key) && object[key].constructor === ({}).constructor) {
this.elements[key] = new UniversalObject(object[key]);
} else if (object.hasOwnProperty(key)) {
this.elements[key] = object[key];
}
}
}
get_by_path(path) {
let key = path.split(DELIMETER)[0]
if (this.elements[key] === undefined) {
return undefined;
} else if (path.split(DELIMETER).length === 1) {
return this.elements[key]
} else {
return this.elements[key].get_by_path(path.substring(path.indexOf('.') + 1, path.length))
}
}
}
/*
In console:
>> u1 = new UniversalObject(dummy_object_complete) // create complete univeral dummy object
<< UniversalObject {elements: {…}}
>> u2 = new UniversalObject(dummy_object_incomplete) // create incomplete universal dummy object
<< UniversalObject {elements: {…}}
>> u1.get_by_path("a.b.b1")
<< 1
>> u2.get_by_path("a.b.b1")
<< undefined // would have caused TypeError in normal circumstances
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment