Getting value of first index within jQuery array using .each() - javascript

I have a JSON array returned via ajax that looks like:
"stuff": [["2","66%"], ["3","42%"],...
Problem
I want to match the zeroth index of each element in this array to a variable outside of the loop and if it matches, I want to return the percentage next to it.
I don't know the syntax in jQuery for this. Please have a look at my code below and see if that's correct or not:
var percentage = 0;
var stuffarr = jsonobj['stuff'];
var stuffID = jsonobj['stuff_id']
if (!stuffID || 0 === stuffID.length){
$("#stuff-element").html("--");
}
else {
var percentage = $.each(stuffarr, function (index, value) {
if(value[0] == stuffID)
return value[1]
});
}

Firstly, a bit of terminology. The data structure you have is an Object which holds several properties. It has nothing to do with JSON after it has been deserialised.
With regard to your issue, there's no jQuery required as you can use find() to find the item in the array by the stuffID variable's value. Try this:
var obj = {
"stuff": [
["2", "66%"],
["3", "42%"]
],
"stuff_id": "3"
}
var percentage = 0;
var stuffArr = obj['stuff'];
var stuffId = obj['stuff_id']
if (!stuffId || 0 === stuffId.length) {
$("#stuff-element").html("--");
} else {
percentage = stuffArr.find(function(el) {
return el[0] == stuffId;
})[1];
}
console.log(percentage);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

try this
var percentage = stuffarr.find(function (value) {
if(value[0] == stuffID)
return value[1];
})[1];

The return statement you used returns the result of the function(..) inside the .each(..) function and is not the return value of the .each(..) function.
the valid return value is boolean which 'tells' the .each(..) function whether it should continue or not. instead use the following syntax:
var ret = '';
$(arr).each(function () {
var curr = $(this);
//console.log(curr);
if(curr[0] == stuffID){
//console.log('>>found: ' + curr[1]);
ret = curr[1];
//if found -> break loop
return false;
}
});
comment: you should consider instead of using an inner array data structure use an object, this is a more 'correct' data structure:
// "stuff": [{"id":"2","percent":"66%"}, {"id":"3","percent":"42%"},...
var ret = '';
$(arr).each(function () {
var curr = this;
//console.log(curr.id);
if(curr.id == stuffID){
//console.log('>>found: ' + curr.percent);
ret = curr.percent;
//if found -> break loop
return false;
}
});
#LiverpoolOwen approach is clean and nice, and if you want to use it combining with the object approach do this:
arr.find(function (value) {
if(value.id == stuffID)
return value;
}).percent;

Related

Array text to numbers, find matching values and sort

I have an array which looks like this:
["1,8", "4,6,8", "8,9", "6,9"]
1/ I would like to turn it in to this
[1,8,4,6,8,8,9,6,9]
2/ I would then like to find matching values, by looking for the most number:
[8]
This first has been solved with this:
var carArray = ["1,8", "4,6,8,7,7,7,7", "8,9", "6,9"];
//1) create single array
var arr = carArray.join().split(',');
//2) find most occurring
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
if(maxOccurring){
//there was an element more than once, maxOccuring contains that element
setResult('Most occuring: ' + maxOccurring + ' (' + max + ' times)');
}
else{
//3)/4) ???
setResult('sorting?');
}
//below is only for test display purposes
function setResult(res){
console.log(res);
}
3/ If the are no matching values like this
[1,8,4,6,5,7]
4/ Then I need to compare this array to another array, such as this
[6,7,4,1,2,8,9,5]
If the first number in <4> array above appears in <3> array, then get that number, ie in the above example I need to get 6. The <4> array will be static values and not change. The numbers is <3> will be dynamic.
EDIT Not the most elegant of answers, but I do have something working now. I didn't compare the original array directly with the second array, instead used simple if/else statements to do what I needed:
var carArray = ["1,5", "4", "8,2", "3,9,1,1,1"];
//1) create single array
var arr = carArray.join().split(',');
//2) find most occurring
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
if(maxOccurring){
//there was an element more than once, maxOccuring contains that element
console.log('Most occuring: ' + maxOccurring + ' (' + max + ' times)');
console.log(maxOccurring);
}
else {
// If not occuring, match from a list
if(jQuery.inArray("6", arr) !== -1) { console.log('6'); }
else if(jQuery.inArray("9", arr) !== -1) { console.log('9'); }
else if(jQuery.inArray("7", arr) !== -1) { console.log('7'); }
else if(jQuery.inArray("5", arr) !== -1) { console.log('5'); }
else if(jQuery.inArray("4", arr) !== -1) { console.log('4'); }
else if(jQuery.inArray("1", arr) !== -1) { console.log('1'); }
else { console.log('not found'); }
}
Example Fiddle
Step 1 is fairly easy by using javascript's join and split methods respectively:
var arr = carArray .join().split(',');
For step 2, several methods can be used, the most common one using an object and using the elements themselves as properties. Since you only need to get the most occurring value if there is a reoccurring value, it can be used in the same loop:
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
After the above, the variable maxOccurring will contain the reoccurring value (if any) and max will contain the times it occured
For step 4 the easiest way is to loop through the compare array and get the element that occurs in the input array:
var cmpArr = ['6','7','4','1','2','8','9','5'];
//find the first occurrence inside the cmpArr
res = function(){ for(var i= 0 ; i < cmpArr.length; i++){ if(arr.indexOf(cmpArr[i]) !== -1)return cmpArr[i];}}();
The above uses an in place function which is called immediately to be able to use return. You could also just use a loop and assign res when found, then break from the loop.
Last update, an alternate fiddle where the above is converted to a single function: http://jsfiddle.net/v9hhsdny/5/
Well first of all the following code results in four matching answers since the jQuery selectors are the same.
var questionAnswer1 = $(this).find('input[name=questionText]').val();
var questionAnswer2 = $(this).find('input[name=questionText]').val();
var questionAnswer3 = $(this).find('input[name=questionText]').val();
var questionAnswer4 = $(this).find('input[name=questionText]').val();
var carArray = [questionAnswer1, questionAnswer2, questionAnswer3, questionAnswer4];
You could use the eq(index) method of jQuery to select the appropriate element. However having 4 inputs with the same name is a bad practice.
Well lets say that the carArray has 4 different values which all consist out of comma separated numbers. You could then do the following:
var newArr = [];
carArray.forEach(function(e) {
e.split(",").forEach(function(n) {
newArr.push(n);
});
});
Well then we got to find the most occurring number. JavaScript doesn't have any functions for that so we will have to find an algorithm for that. I found the following algorithm on this stackoverflow page
var count = function(ary, classifier) {
return ary.reduce(function(counter, item) {
var p = (classifier || String)(item);
counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
return counter;
}, {})
}
var occurances = count(newArr);
It isn't clear to me what you're trying to do in step 3 and 4, so can't answer those at the moment.
var ary = ["1,8", "4,6,8", "8,9", "6,9"];
var splitted = ary.reduce(function(acc, item) {
return acc.concat(item.split(','));
}, []);
var occurences = splitted.reduce(function(acc, item) {
if (!acc.hasOwnProperty(item)) acc[item] = 0;
acc[item] += 1;
return acc;
},{}),
biggest = Object.keys(occurences).reduce(function (acc, key) {
if (occurences[key] > acc.occurences) {
acc.name = key;
acc.occurences = occurences[key];
}
return acc;
},{'name':'none','occurences':0}).name;
var vals=["1,8", "4,6,8", "8,9", "6,9"];
// 1) turn into number array
var arrNew=[];
for(var i=0; i<vals.length; i++)
{
arrLine=vals[i].split(",");
for (var j=0;j<arrLine.length;j++) { arrNew.push (parseInt(arrLine[j])) }
}
//result:
alert(arrNew.join(";");
// 2) find most common
var found=[];
for(var i=0; i<arrNew.length; i++) {
// make an array of the number of occurrances of each value
if (found["num"+newArray[i]]) {
found["num"+newArray[i]] ++ ;
} else {
found["num"+newArray[i]]=1;
}
}
var mostCommon={count:0,val:"ROGUE"};
for (x in found) {
if (found[x] > mostCommon.count) {
mostCommon.count=found[x].count;
mostCommon.val=x;
}
}
// result :
alert(mostCommon.val);
//3) not quite sure what you meant there
// 4) unique values:
// at this point the 'found' list contains unique vals
var arrUnique=[];
for (x in found) {
arrUnique.push[x];
}
// result :
alert(arrUnique.join(";"))
//sort:
arrUnique.sort(function(a, b){return a-b});
(This won't work in most browsers) but on a side note, when ES6 becomes widely supported, your solution could look like this:
var arr1 = ["1,8", "4,6,8", "8,9", "6,9"];
var arr2 = arr1.join().split(',');
var s = Array.from(new Set(arr2)); //Array populated by unique values, ["1", "8", "4", "6", "9"]
Thought you might like to see a glimpse of the future!
1.
var orgArray = ['1,8', '4,6,8', '8,9', '6,9'];
var newArray = [];
for (var i in orgArray) {
var tmpArray = orgArray[i].split(',');
for (var j in tmpArray) {
newArray.push(Number(tmpArray[j]));
}
}
2.
var counts = {};
var most = null;
for (var i in newArray) {
var num = newArray[i];
if (typeof counts[num] === 'undefined') {
counts[num] = 1;
} else {
++(counts[num]);
}
if (most == null || counts[num] > counts[most]) {
most = num;
} else if (most != null && counts[num] === counts[most]) {
most = null;
}
}
I don't understand the question 3 and 4 (what "unique order" means) so I can't answer those questions.

Get unique objects from array based on single attribute

Let's say we have the following:
node[1].name = "apple";
node[1].color = "red";
node[2].name = "cherry";
node[2].color = "red";
node[3].name = "apple";
node[3].color = "green";
node[4].name = "orange";
node[4].color = "orange;
if I use jQuery.unique(node) I will get all the original nodes because they all have a different name OR color. What I want to do is only get the nodes with a unique name, which should return
node[1] (apple)
node[2] (cherry)
node[4] (orange)
It should not return 3 because it is the same fruit, even though we have green and red apples.
Use Array.filter and a temporary array to store the dups:
function filterByName(arr) {
var f = []
return arr.filter(function(n) {
return f.indexOf(n.name) == -1 && f.push(n.name)
})
}
Demo: http://jsfiddle.net/mbest/D6aLV/6/
This approach (forked from #David's) should have better performance for large inputs (because object[] is O(1)).
function filter(arr, attribute) {
var out = [],
seen = {}
return arr.filter(function(n) {
return (seen[n[attribute]] == undefined)
&& (seen[n[attribute]] = 1);
})
}
console.log(filter(node, 'name'));
http://jsfiddle.net/LEBBB/1/
What about doing it like this?
var fruitNames = [];
$.each($.unique(fruits), function(i, fruit) {
if (fruitNames.indexOf(fruit.name) == -1) {
fruitNames.push(fruit.name);
$('#output').append('<div>' + fruit.name + '</div>');
}
});
Here is a working fiddle.
Obviously, instead of output.append I could just add the current fruit to uniqueFruit[] or something.

Javascript deep search and change in object

I have a JavaScript function what is dig through on object and make a string value to function object.
Have this JSON:
{
"active": true,
"icons": {
"activeHeader": "ui-icon-alert"
},
"animate": {
"duration": 1000, "always": "dMethod"
}
}
I use JSON.parse on this string so I reach options.animate.always as a string with value dMethdod which is actually a name of the method. So I can access this through window[options.animate.always] and I wish to change the options.animate.always from string to method that is pointed to the string.
I make a function for this job:
function SetFunctions(options, functionName) {
var path = functionName.split(".");
var setterObject = options;
for (var k = 0; k < path.length; k++) {
if (setterObject != undefined) {
setterObject = setterObject[path[k]];
} else {
break;
}
}
if (setterObject != undefined && window[setterObject] != undefined) {
setterObject = window[setterObject];
}
}
I call this function with the variable returned from the parse and function name animate.always as value.
The part that find the correct property is worked, but when I set the value of the setterObject the change is not affect the original value.
I'm thinking to build up the reference as string 'options.animate.always = dMethod' and use eval on it, but I really want to avoid using eval function (I know eval is evil :)).
FINAL SOULUTION:
I put answers together and finished my method. Finally become two methods. I comment it and share maybe useful to others:
function ChangeStringToFunction(functionPath, rootObject, separator) {
// functionPath is required parameter
if (functionPath === undefined || functionPath === null) return;
// rootObject is optional. If not supplied the window object will be the base of the search
var localRootObject = rootObject === undefined ? window : rootObject;
// separator is optional. If not supplied the '.' will be the separator
var localSeparator = separator === undefined ? "." : separator;
// split the string reference (example "jui.someObj1.someOjb2"
var pathParts = functionPath.split(localSeparator);
var currentObject = localRootObject;
// exclude the last part
for (var i = 0; i < pathParts.length - 1; i++) {
currentObject = currentObject[pathParts[i]];
// it's useless to go forward if there is no object
if (currentObject === undefined) return;
}
// get the string represent the name of the function (full path could be included)
var currentValue = currentObject[pathParts[pathParts.length - 1]];
// the value must be a string
if (typeof currentValue !== "string") return;
// get the function reference based on the value provided
var functionReference = ResolveFunction(currentValue);
// if the result is not a function it's meaningless to continue
if (typeof functionReference !== "function") return;
// and finally change the string value of the object with the function value represent by our string
currentObject[pathParts[pathParts.length - 1]] = functionReference;
}
function ResolveFunction(functionPath, separator, rootObject) {
if (functionPath === undefined || functionPath === null) return undefined;
var localRootObject = rootObject === undefined ? window : rootObject;
var localSeparator = separator === undefined ? "." : separator;
var pathParts = functionPath.split(localSeparator);
var currentObject = localRootObject;
for (var i = 0; i < pathParts.length; i++) {
currentObject = currentObject[pathParts[i]];
if (currentObject === undefined) break;
}
return typeof currentObject === "function" ? currentObject : undefined;
}
but when I set the value of the setterObject the change is not affect the original value.
Yes, you are only assigning to a variable. That will never change anything else but the variable, since JavaScript does not have pointers.
To change an object, you will have to assign to a property. In your case, you will have to omit the last iteration to get the object which you then assign to:
function SetFunctions(options, functionName) {
var path = functionName.split("."),
setterObject = options;
for (var k=0; setterObject!=null && k<path.length-1; k++) {
setterObject = setterObject[path[k]];
}
var prop = path[k],
fn = setterObject!=null && window[setterObject[prop]];
if (fn) {
setterObject[prop] = fn;
}
}
Btw, I think in your case it might be easier to build a CallFunctions function that directly invokes the function with the name stored in that property, instead of replacing the property value with the method - unless you plan to invoke it very often.
It depends on the level of indirection you want.
If the method will always be called "always", you can do something like this:
function SetFunction(object, propertyName, functionName) {
var functionObj = window[functionName];
object[propertyName] = functionObj;
}
And call it like this:
SetFunction(myObj.animate, "always", myObj.animate.always);
But I suspect you want something a bit more generic?

Recursively search for a value in global variables and its properties

Let's say that I want to search for a value, like 'StackOverflow', in all declared variables in window.
I can do it with this code:
function globalSearch(obj, value) {
for(var p in obj)
if(obj[p] == value)
return(p);
}
globalSearch(window, 'StackOverflow');
This code will return the name of a variable that have this value (or returns nothing).
So, if I have declared a variable with value 'StackOverflow', it will successfully find it.
My problem is that I want to go deeper and search thru window's objects (and its own nested objects) too, to achieve a result like this:
var x = 'StackOverflow' // returns 'x'
var y = { a : 'StackOverflow' } // returns 'y.a'
var z = { a : { b: 'StackOverflow' } } // returns 'z.a.b'
I'm having problems with inherited methods of Objects. Is there a way to do this?
Deep search but without the recursive function calls
Functional recursion has internal stack limits and wastes memory.
Additional features added
Recursive object protection in the form of a searched array; It doesn't use up too much memory of course as the objects are only stored as references.
Return true if the the object itself matches the value. Otherwise it would return '' which would match to false.
Arrays use angle-bracket notation.
The code
function globalSearch(startObject, value) {
var stack = [[startObject,'']];
var searched = [];
var found = false;
var isArray = function(test) {
return Object.prototype.toString.call( test ) === '[object Array]';
}
while(stack.length) {
var fromStack = stack.pop();
var obj = fromStack[0];
var address = fromStack[1];
if( typeof obj == typeof value && obj == value) {
var found = address;
break;
}else if(typeof obj == "object" && searched.indexOf(obj) == -1){
if ( isArray(obj) ) {
var prefix = '[';
var postfix = ']';
}else {
var prefix = '.';
var postfix = '';
}
for( i in obj ) {
stack.push( [ obj[i], address + prefix + i + postfix ] );
}
searched.push(obj);
}
}
return found == '' ? true : found;
}
Problems
Without passing the initial variable name into the function, we can't return the fully qualified variable name from the beginning. I can't think of a solution and I would be surprised if there was one.
Variable names with spaces are valid as the key to an object, as are other invalid variable names, it just means that the value must be addressed using angle-brackets. There are a couple of solutions I can think of. Regex check each variable name to make sure it's valid and use angle-brackets notation if it is not. The overriding problem with this is that the reg-ex is a page long. Alternatively, we could only use angle-brackets but this isn't really true to the OPs original question.
The indexOf call on the array 'searched' might be a bit heavy on very large objects but I can't yet think of an alternative.
Improvements
Apart from cleaning up the code a little, it would also be nice if the function returned an array of matches. This also raises another issue in that the returned array would not contain references to recursive objects. Maybe the function could accept a result format configuration parameter.
This should work. It uses recursion to achieve the result.
function globalSearch(obj, value) {
for(var p in obj)
if(obj[p] == value){
return(p);
}else if(typeof obj[p] == "object" && obj[p] != obj){
var te = globalSearch(obj[p], value);
if(te!=false){ return p + "." + te }
}
return false;
}
Make your solution recursive. If you have an object, call your function again.
function globalSearch(obj, value) {
for(var p in obj) {
if (obj[p] == value) {
return(p);
} else if (typeof obj[p] === "object") {
var recursiveCheck= globalSearch(obj[p], value);
if (recursiveCheck) {
return p + "." + recursiveCheck;
}
}
}
}
globalSearch(window, 'StackOverflow');
I bet most browsers will hit a warning for too much looping.
This code, based on the other answer, allows for all possible value matches to be found.
function globalSearch(startObject, value, returnFirstResult = false) {
var stack = [[startObject,'']];
var searched = [];
var found = new Set();
var isArray = function(test) {
return Object.prototype.toString.call( test ) === '[object Array]';
}
while(stack.length) {
var fromStack = stack.pop();
var obj = fromStack[0];
var address = fromStack[1];
if( typeof obj == typeof value && obj == value) {
if (returnFirstResult) {
return address == '' ? false : address;
}
found.add(address)
}if(typeof obj == "object" && searched.indexOf(obj) == -1){
if ( isArray(obj) ) {
var prefix = '[';
var postfix = ']';
}else {
var prefix = '.';
var postfix = '';
}
for( i in obj ) {
stack.push( [ obj[i], address + prefix + i + postfix ] );
}
searched.push(obj);
}
}
return Array.from(found);
}

Parse query string in JavaScript [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I need to parse the query string www.mysite.com/default.aspx?dest=aboutus.aspx.
How do I get the dest variable in JavaScript?
Here is a fast and easy way of parsing query strings in JavaScript:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
Now make a request to page.html?x=Hello:
console.log(getQueryVariable('x'));
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
Turns query string like hello=1&another=2 into object {hello: 1, another: 2}. From there, it's easy to extract the variable you need.
That said, it does not deal with array cases such as "hello=1&hello=2&hello=3". To work with this, you must check whether a property of the object you make exists before adding to it, and turn the value of it into an array, pushing any additional bits.
You can also use the excellent URI.js library by Rodney Rehm. Here's how:-
var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); // == { dest : 'aboutus.aspx' }
alert(qs.dest); // == aboutus.aspx
And to parse the query string of current page:-
var $_GET = URI(document.URL).query(true); // ala PHP
alert($_GET['dest']); // == aboutus.aspx
Me too! http://jsfiddle.net/drzaus/8EE8k/
(Note: without fancy nested or duplicate checking)
deparam = (function(d,x,params,p,i,j) {
return function (qs) {
// start bucket; can't cheat by setting it in scope declaration or it overwrites
params = {};
// remove preceding non-querystring, correct spaces, and split
qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
// march and parse
for (i = qs.length; i > 0;) {
p = qs[--i];
// allow equals in value
j = p.indexOf('=');
// what if no val?
if(j === -1) params[d(p)] = undefined;
else params[d(p.substring(0,j))] = d(p.substring(j+1));
}
return params;
};//-- fn deparam
})(decodeURIComponent, /\+/g);
And tests:
var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';
var $output = document.getElementById('output');
function output(msg) {
msg = Array.prototype.slice.call(arguments, 0).join("\n");
if($output) $output.innerHTML += "\n" + msg + "\n";
else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
var q = deparam(test);
results[msg] = q;
output(msg, test, JSON.stringify(q), $.param(q));
output('-------------------');
});
output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
output(msg, JSON.stringify(result));
output('-------------------');
});
Results in:
simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"} <-- it's there, i swear!
qux=quux&baz=&foo=bar <-- ...see, jQuery found it
-------------------
Here's my version based loosely on Braceyard's version above but parsing into a 'dictionary' and support for search args without '='. In use it in my JQuery $(document).ready() function. The arguments are stored as key/value pairs in argsParsed, which you might want to save somewhere...
'use strict';
function parseQuery(search) {
var args = search.substring(1).split('&');
var argsParsed = {};
var i, arg, kvp, key, value;
for (i=0; i < args.length; i++) {
arg = args[i];
if (-1 === arg.indexOf('=')) {
argsParsed[decodeURIComponent(arg).trim()] = true;
}
else {
kvp = arg.split('=');
key = decodeURIComponent(kvp[0]).trim();
value = decodeURIComponent(kvp[1]).trim();
argsParsed[key] = value;
}
}
return argsParsed;
}
parseQuery(document.location.search);
Following on from my comment to the answer #bobby posted, here is the code I would use:
function parseQuery(str)
{
if(typeof str != "string" || str.length == 0) return {};
var s = str.split("&");
var s_length = s.length;
var bit, query = {}, first, second;
for(var i = 0; i < s_length; i++)
{
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if(first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if(typeof query[first] == "undefined") query[first] = second;
else if(query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
This code takes in the querystring provided (as 'str') and returns an object. The string is split on all occurances of &, resulting in an array. the array is then travsersed and each item in it is split by "=". This results in sub arrays wherein the 0th element is the parameter and the 1st element is the value (or undefined if no = sign). These are mapped to object properties, so for example the string "hello=1&another=2&something" is turned into:
{
hello: "1",
another: "2",
something: undefined
}
In addition, this code notices repeating reoccurances such as "hello=1&hello=2" and converts the result into an array, eg:
{
hello: ["1", "2"]
}
You'll also notice it deals with cases in whih the = sign is not used. It also ignores if there is an equal sign straight after an & symbol.
A bit overkill for the original question, but a reusable solution if you ever need to work with querystrings in javascript :)
If you know that you will only have that one querystring variable you can simply do:
var dest = location.search.replace(/^.*?\=/, '');
The following function will parse the search string with a regular expression, cache the result and return the value of the requested variable:
window.getSearch = function(variable) {
var parsedSearch;
parsedSearch = window.parsedSearch || (function() {
var match, re, ret;
re = /\??(.*?)=([^\&]*)&?/gi;
ret = {};
while (match = re.exec(document.location.search)) {
ret[match[1]] = match[2];
}
return window.parsedSearch = ret;
})();
return parsedSearch[variable];
};
You can either call it once without any parameters and work with the window.parsedSearch object, or call getSearch subsequently.
I haven't fully tested this, the regular expression might still need some tweaking...
How about this?
function getQueryVar(varName){
// Grab and unescape the query string - appending an '&' keeps the RegExp simple
// for the sake of this example.
var queryStr = unescape(window.location.search) + '&';
// Dynamic replacement RegExp
var regex = new RegExp('.*?[&\\?]' + varName + '=(.*?)&.*');
// Apply RegExp to the query string
var val = queryStr.replace(regex, "$1");
// If the string is the same, we didn't find a match - return false
return val == queryStr ? false : val;
}
..then just call it with:
alert('Var "dest" = ' + getQueryVar('dest'));
Cheers
I wanted a simple function that took a URL as an input and returned a map of the query params.
If I were to improve this function, I would support the standard for array data in the URL, and or nested variables.
This should work back and for with the jQuery.param( qparams ) function.
function getQueryParams(url){
var qparams = {},
parts = (url||'').split('?'),
qparts, qpart,
i=0;
if(parts.length <= 1 ){
return qparams;
}else{
qparts = parts[1].split('&');
for(i in qparts){
qpart = qparts[i].split('=');
qparams[decodeURIComponent(qpart[0])] =
decodeURIComponent(qpart[1] || '');
}
}
return qparams;
};
I wanted to pick up specific links within a DOM element on a page, send those users to a redirect page on a timer and then pass them onto the original clicked URL. This is how I did it using regular javascript incorporating one of the methods above.
Page with links: Head
function replaceLinks() {
var content = document.getElementById('mainContent');
var nodes = content.getElementsByTagName('a');
for (var i = 0; i < document.getElementsByTagName('a').length; i++) {
{
href = nodes[i].href;
if (href.indexOf("thisurl.com") != -1) {
nodes[i].href="http://www.thisurl.com/redirect.aspx" + "?url=" + nodes[i];
nodes[i].target="_blank";
}
}
}
}
Body
<body onload="replaceLinks()">
Redirect page
Head
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
function delayer(){
window.location = getQueryVariable('url')
}
Body
<body onload="setTimeout('delayer()', 1000)">

Categories