简体   繁体   中英

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 with an arrow pointing to the first bracket in ( [ ) "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!

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/

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.

The line

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

is not a valid javascript statement.

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.

This looks like an attempt to assign the "key2" property of the "key1" property of nothing to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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