通过传递带有路径和值的字符串来扩展JavaScript对象 [英] Extend a JavaScript object by passing a string with the path and a value
本文介绍了通过传递带有路径和值的字符串来扩展JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有通过传递字符串和值来扩展JavaScript对象的简便方法?
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"
推荐答案
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/
您可以在控制台中看到它根据您输入的path
创建路径.
You can see in the console that it creates the path according to path
you entered.
这篇关于通过传递带有路径和值的字符串来扩展JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文