Created
July 9, 2014 21:33
-
-
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`.
This file contains hidden or 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
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