我有一根线
string = "masterkey[key1][key2]";我想在此基础上创建一个关联数组,以便它的计算结果为:
{
masterkey: {
key1: {
key2: value
}
}
}我已经尝试过了:
var fullName = string;
fullName = fullName.replace(/\[/g, '["');
fullName = fullName.replace(/\]/g, '"]');
eval("var "+fullName+";");但是我得到了一个错误:带有一个指向([) "var masterkey["key1"]["key2"];"中第一个括号的箭头的missing ; before statement
我知道eval()不适合使用,所以如果你有任何建议,最好不要使用它,我真的很感激!
发布于 2012-02-09 17:22:51
不是最美的,但它对我很有效:
var
path = "masterkey[key1][key2]",
scope = {};
function helper(scope, path, value) {
var path = path.split('['), i = 0, lim = path.length;
for (; i < lim; i += 1) {
path[i] = path[i].replace(/\]/g, '');
if (typeof scope[path[i]] === 'undefined') {
scope[path[i]] = {};
}
if (i === lim - 1) {
scope[path[i]] = value;
}
else {
scope = scope[path[i]];
}
}
}
helper(scope, path, 'somevalue');
console.log(scope);演示:http://jsfiddle.net/hR8yM/
发布于 2012-02-09 17:54:56
function parse(s, obj) {
s.match(/\w+/g).reduce(function(o, p) { return o[p] = {} }, obj);
return obj;
}
console.dir(parse("masterkey[key1][key2]", {}))发布于 2012-02-09 17:27:25
现在试试这个
string = "masterkey[key1][key2]";
var fullName = string;
fullName = fullName.replace(/\[/g, '[\'');
fullName = fullName.replace(/\]/g, '\']');
document.write("var "+fullName+";");https://stackoverflow.com/questions/9207920
复制相似问题