[英]set a property's value with unknown depth within an object in javascript
var params = {
search: {
make: "",
model: ""
}
}
function setVariable() {
var value = "BMW";
var key = "search.make";
var arr = key.split("."); //eg. ["search", "make"]
params[arr[0]][arr[1]] = value; // this works, but how do you
// do it with unknown arr[] length?
}
How do I do this with an unknown arr[]
length? 如何使用未知的
arr[]
长度执行此操作?
I have surmised that I probably need to do a recursive call, maybe passing something like arr.slice(1)
within the function, but I have not been able to figure out what that should look like. 我以为我可能需要进行递归调用,可能在函数内传递了类似
arr.slice(1)
之类的东西,但是我一直无法弄清楚应该是什么样子。
The following code traverses your params
object until the given key is found. 以下代码遍历您的
params
对象,直到找到给定的键。 It assumes that key.split(".")
returns a proper array of keys (so you might need to sanitize your inputs here further. 假定
key.split(".")
返回正确的键数组(因此您可能需要在此处进一步清理输入内容。)
var params = {
search: {
make: "",
model: ""
}
}
function setVariable() {
var value = "BMW";
var key = "search.make";
var arr = key.split("."); //eg. ["search", "make"]
var runner = params;
for( var i=0, max=arr.length-1; i<max; ++i ) {
// make sure the key exists
runner[ arr[i] ] = runner[ arr[i] ] || {};
// move one level deeper
runner = runner[ arr[i] ];
}
// set the value in the last level
runner[ arr[arr.length-1] ] = value;
}
EDIT: wrt to the comment of Felix Kling: It assumes that you want previously not existant keys to be generated. 编辑:费利克斯·克林(Felix Kling)的评论:它假定您以前希望不存在要生成的键。 Else you would have to put aa further check into the
for
loop and leave the function, if the key does not exist, instead of creating it. 否则,您将不得不进一步检查
for
循环并保留该函数(如果该键不存在),而不是创建它。
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;
}
Demo: 演示:
> 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' } } }
>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.