简体   繁体   English

将字符串转换为javascript关联数组

[英]Converting a string to a javascript associative array

I have a string 我有一个弦

string = "masterkey[key1][key2]";

I want to create an associative array out of that, so that it evaluates to: 我想从中创建一个关联数组,以便它的计算结果为:

{
  masterkey: {
    key1: {
      key2: value
    }
  }
}

I have tried this: 我已经试过了:

var fullName = string;
fullName = fullName.replace(/\[/g, '["');
fullName = fullName.replace(/\]/g, '"]');
eval("var "+fullName+";");

But I get the error: missing ; before statement 但是我得到了错误: missing ; before statement missing ; before statement with an arrow pointing to the first bracket in ( [ ) "var masterkey["key1"]["key2"];" missing ; before statement ,带有指向( [ )中第一个括号的箭头。 "var masterkey["key1"]["key2"];"

I know that eval() is not good to use, so if you have any suggestions, preferably without using it, I'd really appreciate it! 我知道eval()不好用,所以如果您有任何建议,最好不使用它,我将不胜感激!

Not the most beautiful, but it worked for me: 不是最漂亮的,但对我有用:

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);

demo: http://jsfiddle.net/hR8yM/ 演示: http//jsfiddle.net/hR8yM/

function parse(s, obj) {
    s.match(/\w+/g).reduce(function(o, p) { return o[p] = {} }, obj);
    return obj;
}

console.dir(parse("masterkey[key1][key2]", {}))

Now try this 现在试试这个

string = "masterkey[key1][key2]";
var fullName = string;
fullName = fullName.replace(/\[/g, '[\'');
fullName = fullName.replace(/\]/g, '\']');

document.write("var "+fullName+";");

1) When using eval, the argument you provide must be valid, complete javascript. 1)使用eval时,您提供的参数必须是有效的,完整的javascript。

The line 线

 var masterkey["key1"]["key2"];

is not a valid javascript statement. 不是有效的javascript语句。

When assigning a value to a variable, you must use = . 为变量分配值时,必须使用= Simply concatenating some values on to the end of the variable name will not work. 简单地将一些值连接到变量名的末尾将不起作用。

2) var masterkey = ["key1"]["key2"] doesn't make sense. 2) var masterkey = ["key1"]["key2"]没有意义。

This looks like an attempt to assign the "key2" property of the "key1" property of nothing to masterkey. 这看起来像是尝试将什么都没有的“ key1”属性的“ key2”属性分配给masterkey。

If you want the result to be like the example object you give, then that is what you need to create. 如果您希望结果像您给出的示例对象一样,那就是您需要创建的对象。 That said, parsing the string properly to create an object is better than using regular expressions to translate it into some script to evaluate. 也就是说,正确解析字符串以创建对象比使用正则表达式将其转换为要评估的脚本更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM