I have a string like this:
string = "locations[0][street]=street&locations[0][street_no]=
34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
What must I do with this string so i can play with locations[][] as I wish?
gideon
19.5k11 gold badges74 silver badges114 bronze badges
2 Answers 2
You could write a parser:
var myStr = "locations[0][street]=street&locations[0][street_no]=34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
function parseArray(str) {
var arr = new Array();
var tmp = myStr.split('&');
var lastIdx;
for (var i = 0; i < tmp.length; i++) {
var parts = tmp[i].split('=');
var m = parts[0].match(/\[[\w]+\]/g);
var idx = m[0].substring(1, m[0].length - 1);
var key = m[1].substring(1, m[1].length - 1);
if (lastIdx != idx) {
lastIdx = idx;
arr.push({});
}
arr[idx * 1][key] = parts[1];
}
return arr;
}
var myArr = parseArray(myStr);
Sign up to request clarification or add additional context in comments.
6 Comments
Joe
+1 nice solution, although I think you meant
push and not addBrian
@Joey - push is the instance method, which also would work. Array.add(instance, value) is adds a new index to an array.
Leth
it throws this: Uncaught TypeError: Object function Array() { [native code] } has no method 'add', tried push, same error
Joe
I'm just not sure you're getting much browser coverage with that, but either way.
Brian
@Joey - touche! Gomoi got precisely what you were talking about... will update w/ push, not .add..
|
As Shadow wizard said, using split and eval seems to be the solution. You need to initialize locations first, if you want to avoid an error.
stringArray=string.split("&");
for (var i=0;i<stringArray.length;i++){
eval(stringArray[i]);
}
However, you might need to pay attention to what street and street_no are. As is, it will produce an error because street is not defined.
Edit: and you'll need to fully initialize locations with as many item as you'll have to avoid an error.
answered Aug 1, 2011 at 13:21
Py.
3,6091 gold badge36 silver badges55 bronze badges
2 Comments
James Montagne
Be very careful using eval like this with a string coming from an external source. Unless the source is 100% trusted this is very dangerous.
Py.
Yeah, i know this is some dangerous stuff, I try to avoid using it unless it's the only way (or if it's easier than the rest by far). Using regexp like Brian did seems a safer (and cleaner) way but a longer one.
lang-js
splitusing&as delimeter then useevalto evaluate each part. Can't you have more "proper" data source though?