假设我们只给
var obj = {};
var propName = "foo.bar.foobar";
我们如何将属性obj.foo.bar.foobar
设置为某个值(比如“hello world”)?所以我想实现这一点,而我们只有一个字符串中的属性名称:
obj.foo.bar.foobar = "hello world";
假设我们只给
var obj = {};
var propName = "foo.bar.foobar";
我们如何将属性obj.foo.bar.foobar
设置为某个值(比如“hello world”)?所以我想实现这一点,而我们只有一个字符串中的属性名称:
obj.foo.bar.foobar = "hello world";
function assign(obj, prop, value) {
if (typeof prop === "string")
prop = prop.split(".");
if (prop.length > 1) {
var e = prop.shift();
assign(obj[e] =
Object.prototype.toString.call(obj[e]) === "[object Object]"
? obj[e]
: {},
prop,
value);
} else
obj[prop[0]] = value;
}
var obj = {},
propName = "foo.bar.foobar";
assign(obj, propName, "Value");
由于这个问题似乎是由错误答案回答的,我将参考类似问题中的正确答案
function setDeepValue(obj, value, path) {
if (typeof path === "string") {
var path = path.split('.');
}
if(path.length > 1){
var p=path.shift();
if(obj[p]==null || typeof obj[p]!== 'object'){
obj[p] = {};
}
setDeepValue(obj[p], value, path);
}else{
obj[path[0]] = value;
}
}
用:
var obj = {};
setDeepValue(obj, 'Hello World', 'foo.bar.foobar');
编辑:我创建了一个jsPerf.com 测试用例来将接受的答案与我的版本进行比较。事实证明,我的版本更快,尤其是当你深入时。
var nestedObjectAssignmentFor = function(obj, propString, value) {
var propNames = propString.split('.'),
propLength = propNames.length-1,
tmpObj = obj;
for (var i = 0; i <= propLength ; i++) {
tmpObj = tmpObj[propNames[i]] = i !== propLength ? {} : value;
}
return obj;
}
var obj = nestedObjectAssignment({},"foo.bar.foobar","hello world");
所有解决方案在设置时都覆盖了任何原始数据,因此我对以下内容进行了调整,使其也成为单个对象:
var obj = {}
nestObject.set(obj, "a.b", "foo");
nestObject.get(obj, "a.b"); // returns foo
var nestedObject = {
set: function(obj, propString, value) {
var propNames = propString.split('.'),
propLength = propNames.length-1,
tmpObj = obj;
for (var i = 0; i <= propLength ; i++) {
if (i === propLength){
if(tmpObj[propNames[i]]){
tmpObj[propNames[i]] = value;
}else{
tmpObj[propNames[i]] = value;
}
}else{
if(tmpObj[propNames[i]]){
tmpObj = tmpObj[propNames[i]];
}else{
tmpObj = tmpObj[propNames[i]] = {};
}
}
}
return obj;
},
get: function(obj, propString){
var propNames = propString.split('.'),
propLength = propNames.length-1,
tmpObj = obj;
for (var i = 0; i <= propLength ; i++) {
if(tmpObj[propNames[i]]){
tmpObj = tmpObj[propNames[i]];
}else{
break;
}
}
return tmpObj;
}
};
也可以将函数更改为 Oject.prototype 方法,将 obj 参数更改为:
Object.prototype = { setNested = function(){ ... }, getNested = function(){ ... } }
{}.setNested('a.c','foo')