1

I have this as data input (it's dynamic so it can be 1 up to 5 brackets in the same string)

data["optionBase"] = {} //declaration
data["optionBase"]["option"] = {} //declaration
data["optionBase"]["option"][value] = {} //declaration
data["optionBase"]["option"][value]["detail"] = somethingHere

Each line comes as a string, not as an array or any other type of javascript object. How can i get an array out of that string containing something like this:

Line 1:

result[0] = "optionBase"

Line 2:

result[0] = "optionBase"
result[1] = "option"

Line 3:

result[0] = "optionBase"
result[1] = "option"
result[2] = value

Line 4:

result[0] = "optionBase"
result[1] = "option"
result[2] = value
result[3] = "detail"
2
  • why not just eval(string) and your data can be traversed as a multi-dimensional array: var data = {}; eval(string); Commented Sep 5, 2010 at 6:35
  • I need the values as text so i call another process, that's why i don't need the array itself, i need what's between brackets as strings Commented Sep 5, 2010 at 6:57

1 Answer 1

1
var s1 = 'data["optionBase"] = {} //declaration';
var s2 = 'data["optionBase"]["option"] = {} //declaration';
var s3 = 'data["optionBase"]["option"][value] = {} //declaration';
var s4 = 'data["optionBase"]["option"][value]["detail"] = somethingHere';
var a = [s1, s2, s3, s4];
var regex = /data\[([^\]]+)\](?:\[([^\]]+)\])?(?:\[([^\]]+)\])?(?:\[([^\]]+)\])?/;
for(var i = 0; i < 4; i++)
{
  var result = a[i].match(regex);
  //result[0] contains the whole matched string
  for(var j = 0; j < 5; j++)
    console.log(result[j]);
}

If you want to make it dynamic, you can extract the string and split around ][

var s = 'data["optionBase"]["option"][value]["detail"] = somethingHere';
var m = s.match(/data((?:\[[^\]]+\])+)/);
var substr = m[1].substring(1, m[1].length - 1);
var array = substr.split("][");
console.log(array);
Sign up to request clarification or add additional context in comments.

3 Comments

This looks good, i think it's close to what i want up to 90%, but is there a way to make the regexp dynamic? with your regexp it's limited to 4 brackets right? if the data input grows it will not get the value. If it's not possible guess i'll take this solution
Excellent, works like a charm, however i found out that using m[1].length - 1 instead of -2 gives me exactly what i have inside the brackets, with -2 it removed the last " of the value. Thanks for your help
@Kus Fixed it. I was confused between string.substring and string.substr it seems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.