I need to take a query string (example: ?name=value1&type=value2&name=value3&type=value4...
but this code should be able to handle any query string passed to it) and create an object from it.
I have nearly completed a function that does this. However, my logic is a bit off inside that last for loop. If someone could please point out where I've gone wrong I'd really appreciate it!
First I grab the query string using jQuery's $.get
function:
$.get("xmlreader.php", function(data) {
var queryParams = [];
var qString = data;
// test qString for & at the end
var last = qString.lastIndexOf("&");
if(last == qString.length - 1) {
// then there is a & to remove
qString = qString.substring(0,qString.length-1);
}
getParamObj(qString);
});
(I know it's funky that I remove the last & here in my JavaScript but I don't want to focus on that here at all.)
Then I call getParamObject(qString);
to build the actual collection object:
function getParamObj(parameterString) {
var qString = parameterString;
var parameters = qString.split("&");
parameters[0] = parameters[0].substring(1);
var paramObject = new Object();
for(var index = 0; index < parameters.length; ++index) {
var equalsPos = parameters[index].indexOf("=");
var key = parameters[index].substring(0,equalsPos);
var stringLength = parameters[index].length;
var value = parameters[index].substring(equalsPos + 1, stringLength);
if(!paramObject[key]) {
console.log("paramObject[key] = " + paramObject[key]);
paramObject[key] = value;
if(paramObject[key] instanceof Array ) {
console.log("instance of array");
paramObject[key].push(value);
} else {
var newArray = [];
var existingValue = paramObject[key];
console.log("existing value: " + existingValue);
console.log("value: " + value);
newArray.push(existingValue);
newArray.push(value);
paramObject[key] = newArray;
}
}
}
The function is working -almost- correctly. A couple things are wrong when I test it: in the last conditional existingValue and value are the same. There may be other issues as well but I think that's the primary one.
I've seen approaches that use regular expressions but I DON'T want to take that route here.
Note: I've answered my own question LOL... stack won't let me comment this because I'm not cool enough yet at just 58 rep :)
[code]
if(!paramObject[key]) {
console.log("paramObject[key] = " + paramObject[key]);
paramObject[key] = value;
console.log("paramObject[key] = value = " + value + paramObject[key]);
console.log(paramObject[key]);
}
else if(paramObject[key] instanceof Array ) {
paramObject[key].push(value);
console.log("value if arra" + value);
} else {
var newArray = [];
var existingValue = paramObject[key];
console.log("existing value: " + existingValue);
console.log("value: " + value);
newArray.push(existingValue);
newArray.push(value);
paramObject[key] = newArray;
}
[/code]
paramObject[key] = value;
andvar existingValue = paramObject[key];
you're basically doingvar existingValue = value
aren't you?