Skip to content

Instantly share code, notes, and snippets.

@tjunghans
Created February 9, 2016 12:11
Show Gist options
  • Save tjunghans/33567299e96ac0c85c1a to your computer and use it in GitHub Desktop.
Save tjunghans/33567299e96ac0c85c1a to your computer and use it in GitHub Desktop.
Get the value of an object property where the property is a string consisting either of the name or changed hierarchy
console.clear();
var obj = {
namespace: {
foo: "123"
}
};
function getPropVal(obj, prop) {
var levels = prop.split(".");
if (levels.length === 1) { return obj[levels[0]]; }
isUndefined = false;
var val = levels.reduce(function (prev, next) {
if (prev[next] === undefined) { isUndefined = true; }
return prev[next] || {};
}, obj);
if (isUndefined) {
return;
} else {
return val;
}
}
console.log(getPropVal({}, "namespace.foo")); //undefined
console.log(getPropVal(obj, "namespace.foo")); //123
function setPropVal(obj, prop, val) {
var levels = prop.split(".");
var len = levels.length;
var current = obj;
levels.forEach(function (level, index) {
if (index === len - 1) {
current[level] = val;
}
if (current[level] === undefined) {
current[level] = {};
}
current = current[level];
});
}
var obj2 = {};
setPropVal(obj, "namespace.foo", "456");
console.log(obj.namespace.foo); //456
setPropVal(obj2, "namespace.foo", "456");
console.log(obj2.namespace.foo); //456
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment