Forum Moderators: open

Message Too Old, No Replies

Converting A String To An Array

         

MartinWeb

3:56 am on Nov 14, 2010 (gmt 0)

10+ Year Member



Hello.

If I have the string "5-3-6", how can I convert that to get the content of the multi-level array a[5][3][6]?

The code must be flexible, and must be able to work on strings such as "3-2" or "6-3-3-7-4", with no limit on the string's length.

Any help would be greatly appreciated. Thank you!

Fotiman

4:06 pm on Nov 14, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



There are a couple different approaches you could take. For example, you could convert the string "5-3-6" into "[5][3][6]" and then use eval to evaluate it. But I generally advise against using eval.

Here's how I'd do it. I'd start by getting the values I care about from the string. Since I know that the values will always be separated by the "-" character, and since I don't know how many values there will be, the string.split seems like a good choice, which will put the values into an array. From there, I would iterate through the array until I had the element I wanted. For example:

var sampleString = "5-3-6",
values = sampleString.split("-"),
i,
n = values.length,
myObj = a; // a is defined elsewhere
for (i = 0; i < n; i++) {
myObj = myObj[parseInt(i,10)];
}
// myObj = a[5][3][6]

I didn't try it, but I *think* that does what you want. :)

ppeterson

10:07 pm on Nov 14, 2010 (gmt 0)

10+ Year Member



Here's a way that doesn't involve eval().

function strToLevels(arr, str) { 

var parts, curArr, x;

parts = str.split("-");

curArr = arr;

for (x = 0; x < parts.length; x = x + 1) {
curArr = curArr[parseInt(parts[x], 10)];
}

return curArr;

}

var myarr = ["0", ["a", "b", ["x", ["q"], "z"]], "2"];

alert(strToLevels(myarr, "1-2-1-0")); // returns "q"