Skip to content

Instantly share code, notes, and snippets.

@derpycoder
Last active March 4, 2020 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derpycoder/8326ba7952229f642d59c9ef297ad796 to your computer and use it in GitHub Desktop.
Save derpycoder/8326ba7952229f642d59c9ef297ad796 to your computer and use it in GitHub Desktop.
Accessing Deep Properties from Objects
var obj = {
x: {
p: [
{
q: [
"Foo Bar"
]
}
]
}
};
/**
* Returns value if it exists,
* else returns default
*/
function getProp(obj, props, def) {
let o = obj;
props.forEach(prop => {
o = o[prop] ? o[prop] : def;
});
return o;
}
/**
* Sets value even if it doesn't exists
*/
function setProp(obj, props, val) {
let o = obj, i;
for (i = 0; i < props.length - 1; i++) {
if (o[props[i]] != null) {
o = o[props[i]];
continue;
}
return;
}
o[props[i]] = val;
}
console.log("Metasyntactic Vars: ");
console.log("Others: ", getProp(obj, ["x", "p", 0, "q", 0], "NA"));
setProp(obj, ["x", "p", 0, "q", 1], "Mew Mau");
console.log("Mine ", getProp(obj, ["x", "p", 0, "q", 1], "NA"));
@derpycoder
Copy link
Author

Actually, after writing the code, I found out about
Lodash Get

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment