Last active
March 4, 2020 13:51
-
-
Save derpycoder/8326ba7952229f642d59c9ef297ad796 to your computer and use it in GitHub Desktop.
Accessing Deep Properties from Objects
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
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")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Actually, after writing the code, I found out about
Lodash Get