给定一个对象x={a:1,b:2}和一个字符串c.d=3,将对象x修改为以下内容:
{
a:1,
b:2,
c:{
d:3
}
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种不使用的解决方案eval.用例如下:
x 作为配置对象,我们称之为:
config.set("music.shuffle",true)
现在,music.shuffle必须以某种方式解析并添加到xconfig.set函数内的内部对象,以便x看起来像:
x={a:1,b:2,music:{shuffle:true}}
Run Code Online (Sandbox Code Playgroud)
nnn*_*nnn 10
在我的脑海中,我猜你可以这样做:
function addValueToObj(obj, newProp) {
newProp = newProp.split("="); // separate the "path" from the "value"
var path = newProp[0].split("."), // separate each step in the "path"
val = newProp.slice(1).join("="); // allow for "=" in "value"
for (var i = 0, tmp = obj; i < path.length - 1; i++) {
tmp = tmp[path[i]] = {}; // loop through each part of the path adding to obj
}
tmp[path[i]] = val; // at the end of the chain add the value in
}
var x = {a:1, b:2};
addValueToObj(x, "c.d=3");
// x is now {"a":1,"b":2,"c":{"d":"3"}}
addValueToObj(x, "e.f.g.h=9=9");
// x is now {"a":1,"b":2,"c":{"d":"3"},"e":{"f":{"g":{"h":"9=9"}}}}
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/E8dMF/1/
你可以这样做 lodash.set()
> l=require('lodash')
> x={a:1,b:2};
{ a: 1, b: 2 }
> l.set(x, 'c.d', 3)
{ a: 1, b: 2, c: { d: 3 } }
| 归档时间: |
|
| 查看次数: |
4422 次 |
| 最近记录: |