Skip to content

Instantly share code, notes, and snippets.

@thure
Created July 9, 2014 21:33
Show Gist options
  • Save thure/aec6c999d0127ffeb36f to your computer and use it in GitHub Desktop.
Save thure/aec6c999d0127ffeb36f to your computer and use it in GitHub Desktop.
A function that extends an object given a path of properties, e.g. `opath(obj, 'one', 'two', 'three', null)`. Requires underscore.js to be available at `us`.
function opath(){
var args = Array.prototype.slice.call(arguments);
var object = args.shift()
, val = args.pop();
if(args.length > 0){
us.each(args, function(arg, i){
var cur;
if(i === 0){
cur = object;
}else{
cur = eval('object["' + args.slice(0, i).join('"]["') + '"]');
}
if(!us.has(cur, arg) && i+1 === args.length){
eval('object["' + args.slice(0, i+1).join('"]["') + '"] = val');
}else if((us.has(cur, arg) && !us.isObject(cur[arg])) || !us.has(cur, arg)){
eval('object["' + args.slice(0, i+1).join('"]["') + '"] = {}');
}
})
}else{
object = val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment