var params = {
search: {
make: "",
model: "",
whatever: {
foo: {
bar: {
moo: 123,
meow: 'xyz'
}
}
}
}
};
function updatePath(obj, path, value) {
var parts = path.split('.');
var i, tmp;
for(i = 0; i < parts.length; i++) {
tmp = obj[parts[i]];
if(value !== undefined && i == parts.length - 1) {
tmp = obj[parts[i]] = value;
}
else if(tmp === undefined) {
tmp = obj[parts[i]] = {};
}
obj = tmp;
}
return obj;
}
演示:
> updatePath(params, 'search.whatever.foo.bar')
{ moo: 123, meow: 'xyz' }
> updatePath(params, 'search.whatever.foo.bar.moo')
123
> updatePath(params, 'search.whatever.foo.bar.moo', 'test')
'test'
> updatePath(params, 'search.whatever.foo.bar.moo')
'test'
> updatePath(params, 'search.whatever.foo.bar')
{ moo: 'test', meow: 'xyz' }
> updatePath(params, 'search.whatever.foo.bar.x.y.z', 'hi')
'hi'
> updatePath(params, 'search.whatever.foo.bar.x')
{ y: { z: 'hi' } }
> updatePath(params, 'search.whatever.foo.bar')
{ moo: 'test',
meow: 'xyz',
x: { y: { z: 'hi' } } }
>
如果'search'甚至不存在?你想創建對象'{make:value}'然後將它分配給'params.search'?或者你只想設置*現有*屬性的值? – 2012-03-04 11:29:39