问题
Is there an easy way to extend a JavaScript object by passing a string and a value?
Basically I need something like this:
myObject = {}
var extendObj = function(obj, path, value){
}
var path = "a.b.c", value = "ciao";
extendObj(myObject, path, value);
console.log(myObject.a.b.c) //will print "ciao"
回答1:
myObject = {};
var extendObj = function (obj, path, value) {
var levels = path.split("."),
i = 0;
function createLevel(child) {
var name = levels[i++];
if(typeof child[name] !== "undefined" && child[name] !== null) {
if(typeof child[name] !== "object" && typeof child[name] !== "function") {
console.warn("Rewriting " + name);
child[name] = {};
}
} else {
child[name] = {};
}
if(i == levels.length) {
child[name] = value;
} else {
createLevel(child[name]);
}
}
createLevel(obj);
return obj;
}
var path = "a.b.c",
value = "ciao";
extendObj(myObject, path, value);
console.log(myObject.a.b.c) //will print "ciao"
http://jsfiddle.net/DerekL/AKB4Q/
You can see in the console that it creates the path according to path
you entered.
来源:https://stackoverflow.com/questions/16182141/extend-a-javascript-object-by-passing-a-string-with-the-path-and-a-value