Convert URL params (inline and after ?) to object with JavaScript - javascript

I'm looking at creating a vanilla JavaScript function which creates an object of parameters from URL path definition given a specific URL path. Very similar to how AngularJS does it as part of the routeParams service. For example...
Given the following path definition:
/page1/{id}
And the actual URL path of:
/page1/23?fname=Jon&lname=Doe
I would like to create the following object:
{
"id": 23,
"fname": "Jon",
"lname": "Doe"
}
Any help would be greatly appreciated.

This is what I was looking for. It is a very rough example and the code could obviously be optimised and cleaned up however.
function getParams(route, path) {
var result = {};
var queryString = (path.indexOf("?") > -1) ? path.substr(path.indexOf("?") + 1, path.length) : null;
queryString.split("&").forEach(function(part) {
if(!part) return;
part = part.replace("+"," ");
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]");
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
var re = /{(\w+)}/g;
var results = [];
while (match = re.exec(route)) {
results.push(match[1]);
}
var re2 = /\/page1\/id\/(\w+)\/name\/(\w+)/g;
var results2 = re2.exec(path);
for (var i = 0; i < results.length; i++) {
result[results[i]] = results2[i + 1];
}
return result;
}
var route = "/page1/id/{id}/name/{name}";
var path = "/page1/id/23/name/leon?fname=Jon&lname=Doe";
var params = getParams(route, path);
console.log("PARAMS:", params);
The above code outputs:
PARAMS: Object {fname: "Jon", lname: "Doe", id: "23", name: "leon"}

Related

How can I get complex URI query string parameters in native JavaScript like in PHP?

My question is about full power solution for parsing ANY complex URI parameters using just normal browser's Javascript. Like it do PHP, for simple code compatibility between JS and PHP sources.
But the first, let us see some particular known decisions:
1.
There is popular question and answers on StackOverflow, see How can I get query string values in JavaScript?
You can find there quite simple solutions for common SIMPLE cases. For example, like handling this scalar parameters like this one:
https://example.com/?name=Jonathan&age=18
It has no answers for handling complex query params. (As far as I could see for answers with source codes and author comments)
2.
Also you may use an URL object in modern browsers, see https://developer.mozilla.org/en-US/docs/Web/API/URL, or exactly https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams
It is enought powerful and you don't need to write or load any code for parsing URI parameters - just use
var params = (new URL(document.location)).searchParams;
var name = params.get("name"); // is the string "Jonathan"
var age = parseInt(params.get("age")); // is the number 18
This approach has such disadvantage that URL is available only in most of modern browsers, - other browsers or outdated versions of browsers will fail.
So, what I need. I need parsing any complex URI params, like
https://example.com/?a=edit&u[name]=Jonathan&u[age]=18&area[]=1&area[]=20&u[own][]=car&u[own][]=bike&u[funname]=O%27Neel%20mc%20Fly&empty=&nulparam&the%20message=Hello%20World
to
{
'a': 'edit',
'u': {
'name': 'Jonathan',
'age': '18',
'own': ['car', 'bike'],
'funname': 'O\'Neel mc Fly'
},
'area': [1, 20],
'empty': '',
'nulparam': null,
'the message': 'Hello World'
}
Preferrable answer is just plain readable javascript source. Simple and small wide-used library can be accepted too, but this question is not about them.
`
PS:
To start I just publish my own current solution for parsing URI params and vice versa for making URI from params. Any comments for it are welcome.
Hope this helps to save time for lot of coders later.
My solution
Usage:
var params = getQueryParams(location.search);
var params = getQueryParams();
var params = {...};
var path = '...';
var url = path;
var urlSearch = getQueryString(params);
if (urlSearch) {
url += '?' + urlSearch;
}
history.replaceState({"autoUrl": url}, "autoreplace", url);
Code:
function getQueryParams(qs) {
if (typeof qs === 'undefined') {
qs = location.search;
}
qs = qs.replace(/\+/g, ' ');
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
var name = decodeURIComponent(tokens[1]);
var value = decodeURIComponent(tokens[2]);
if (value.length == 0) {
continue;
}
if (name.substr(-2) == '[]') {
name = name.substr(0, name.length - 2);
if (typeof params[name] === 'undefined') {
params[name] = [];
}
if (value === '') {
continue;
}
params[name].push(value);
continue;
}
if (name.substr(-1) == ']') {
var nameParts = name.split('[');
name = nameParts[0];
for (var i = 1; i < nameParts.length; i++) {
nameParts[i] = nameParts[i].substr(0, nameParts[i].length - 1);
}
var ptr = params;
for (var i = 0; i < nameParts.length - 1; i++) {
name = nameParts[i];
if (typeof ptr[name] === 'undefined') {
ptr[name] = {};
}
ptr = ptr[name];
}
name = nameParts[nameParts.length - 1];
ptr[name] = value;
continue;
}
params[name] = value;
}
return params;
}
function getQueryString(params) {
var paramsStringParts = [];
for (var name in params) {
if (params[name] instanceof Array) {
paramsStringParts.push( name + '[]=' + params[name].join('&' + name + '[]=') );
} else if (typeof params[name] === 'object') {
var makeFlattern = function(obj){
var result = [];
if (obj instanceof Array) {
for (var i = 0; i < obj.length; i++) {
result.push('[]=' + obj[i]);
}
return result;
}
for (var i in obj) {
if (typeof obj[i] === 'object') {
var subResult = makeFlattern(obj[i]);
for (var j = 0; j < subResult.length; j++) {
result.push('[' + i + ']' + subResult[j]);
}
continue;
}
result.push('[' + i + ']=' + obj[i]);
}
return result;
};
paramsStringParts.push( name + makeFlattern(params[name]).join('&' + name) );
} else {
paramsStringParts.push( name + '=' + params[name] );
}
}
return paramsStringParts.join('&');
}
A bit late, but just struggled over the same problem, solution was very simple:
use encodeURIComponent(...) for the stringified complex objects, the result can then be used as normal queryString-Part.
In the result-side the query-string-parameters have to be un-stringified.
Example:
var complex_param_obj = {
value1: 'Wert1',
value2:4711
};
console.log(restored_param_obj);
var complex_param_str = encodeURIComponent(JSON.stringify(complex_param_obj));
console.log(complex_param_str);
var complex_param_url = 'http://test_page.html?complex_param=' + complex_param_str;
//on the result-side you would use something to extract the complex_param-attribute from the URL
//in this test-case:
var restored_param_obj = decodeURIComponent(complex_param_str);
console.log(restored_param_obj);

Get variables from URL and convert to array

I need to retrieve variables from an URL.
I use this found function:
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
The output is:
{"idPagamenti":["26","27"],"idCliente":["9"]}
But idCliente is always NOT an array, so i'd like to retrieve:
{"idPagamenti":["26","27"],"idCliente": 9 }
This is the fiddle example
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var stringa = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
$(document).ready(function(){
alert("testing");
console.log(me);
$(".a").html(JSON.stringify(me));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
</div>
Someone can help me to modify code?
I think your facing a real paradigm problem. Why idCliente wouldn't be an array but idPagamenti would be. You should have all array or none but not both. getParams() function can make this choice for you and you should probably change the way you are working with this.
Anyway, here is a getParams() function that replace any single-valued array to a value. Note that if you have only one idPagamenti in your URI, you will also have a single value for idPagamenti instead of an array.
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
Object.keys(obj).forEach(key => {
if (obj[key].length === 1) {
obj[key] = obj[key][0];
}
})
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
If you know that you will always get ids as parameters, you can also add a parseInt() for each parameter by replacing var value = spl[1]; with var value = parseInt(spl[1], 10);

Javascript: group JSON objects using specific key

I have the following JSON object and wanted to merge them by OrderID, making the items into array of objects:
[
{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
},
{
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}
]
and I'm wondering how in Javascript to merge the items on the same order...like this:
[{
"OrderID": "999123",
"Items": [{
"ItemCode": "DY-FBBO",
"ItemQuantity": "2",
"ItemName": "DOIY Foosball Bottle Opener > Red",
"ItemPrice": "34.95"
}, {
"ItemCode": "TED-072",
"ItemQuantity": "1",
"ItemName": "Ted Baker Womens Manicure Set",
"ItemPrice": "74.95"
}]
}]
I suggest you use javascript library like underscorejs/lazyjs/lodash to solve this kind of thing.
Here is the example on using underscorejs:
var data = [{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
}, {
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}]
var result = _.chain(data).groupBy(function (e) {
return e.OrderID;
}).map(function (val, key) {
return {
OrderID: key,
Items: _.map(val, function (eachItem) {
delete eachItem.OrderID;
return eachItem;
})
};
}).value();
Working example:
var data = [{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
}, {
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}];
var result = _.chain(data).groupBy(function (e) {
return e.OrderID;
}).map(function (val, key) {
return {
OrderID: key,
Items: _.map(val, function (eachItem) {
delete eachItem.OrderID;
return eachItem;
})
};
}).value();
document.write(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
This should do what you want it to do, but it's rather a group function than a merge function :)
You can see the result in the browser console.
var items = [
{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
},
{
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}
];
function groupBy(ungrouped, groupByProperty) {
var result = [],
getGroup = function (arr, val, groupByProperty) {
var result, j, jlen;
for (j = 0, jlen = arr.length; j < jlen; j++) {
if (arr[j][groupByProperty] === val) {
result = arr[j];
break;
}
}
if (!result) {
result = {};
result.items = [];
result[groupByProperty] = val;
arr.push(result);
}
return result;
}, i, len, item;
for (i = 0, len = ungrouped.length; i < len; i++) {
item = getGroup(result, ungrouped[i][groupByProperty], groupByProperty);
delete ungrouped[i][groupByProperty];
item.items.push(ungrouped[i]);
}
return result;
}
var grouped = groupBy(items, 'OrderID');
document.getElementById('result').innerHTML = JSON.stringify(grouped);
console.log(grouped);
<div id="result"></div>
Lodash is a great Javascript Utility library that can help you in this case. Include the latest version of lodash in your code and group the objects like this:
var mergedOrders = _.groupBy(OriginalOrders, 'OrderID');
It seems you'll have to do a function that, for each entry, will check if it match
try this :
// your array is oldArr
var newArr = []
for (var i=0;i<oldArr.length;i++){
var found = false;
for(var j=0;j<newArr.length;j++){
if(oldArr[i]["OrderID"]==newArr[j]["OrderID"]){
newArr[j]["Items"].push(oldArr[i]);
found=true;
break;
}
if(!found){
newArr.push({"OrderID" : oldArr[i]["OrderID"], "Items" : oldArr[i]});
}
}
You need to loop and create new grouped objects according to your requirement.
For an easier approach I would suggest using jquery-linq
var qOrderIds = $.Enumerable.From(myArray).Select(function(item) { return item.OrderID; }).Distinct();
var groupedList = qOrderIds.Select(function(orderId) {
return {
OrderID: orderId,
Items : $.Enumerable.From(myArray).Where(function(item) { item.OrderID === orderId}).ToArray()
};
}).ToArray();
Thank you for all your answers.
I was able to attain my goal (maybe a bit dirty and not as beautiful as yours but it worked on my end). Hoping this might help others in the future:
function processJsonObj2(dataObj, cfg) {
var retVal = dataObj.reduce(function(x, y, i, array) {
if (x[cfg.colOrderId] === y[cfg.colOrderId]) {
var orderId = x[cfg.colOrderId];
var addressee = x[cfg.colAddressee];
var company = x[cfg.colCompany];
var addr1 = x[cfg.colAddress1];
var addr2 = x[cfg.colAddress2];
var suburb = x[cfg.colSuburb];
var state = x[cfg.colState];
var postcode = x[cfg.colPostcode];
var country = x[cfg.colCountry];
var orderMsg = x[cfg.colOrderMessage];
var carrier = x[cfg.colCarrier];
delete x[cfg.colOrderId];
delete y[cfg.colOrderId];
delete x[cfg.colAddressee];
delete y[cfg.colAddressee];
delete x[cfg.colCompany];
delete y[cfg.colCompany];
delete x[cfg.colAddress1];
delete y[cfg.colAddress1];
delete x[cfg.colAddress2];
delete y[cfg.colAddress2];
delete x[cfg.colSuburb];
delete y[cfg.colSuburb];
delete x[cfg.colState];
delete y[cfg.colState];
delete x[cfg.colPostcode];
delete y[cfg.colPostcode];
delete x[cfg.colCountry];
delete y[cfg.colCountry];
delete x[cfg.colOrderMessage];
delete y[cfg.colOrderMessage];
delete x[cfg.colCarrier];
delete y[cfg.colCarrier];
var orderObj = {};
orderObj[cfg.colOrderId] = orderId;
orderObj[cfg.colAddressee] = addressee;
orderObj[cfg.colCompany] = company;
orderObj[cfg.colAddress1] = addr1;
orderObj[cfg.colAddress2] = addr2;
orderObj[cfg.colSuburb] = suburb;
orderObj[cfg.colState] = state;
orderObj[cfg.colPostcode] = postcode;
orderObj[cfg.colCountry] = country;
orderObj[cfg.colOrderMessage] = orderMsg;
orderObj[cfg.colCarrier] = carrier;
orderObj["Items"] = [ x, y ];
return orderObj;
} else {
var orderId = x[cfg.colOrderId];
var addressee = x[cfg.colAddressee];
var company = x[cfg.colCompany];
var addr1 = x[cfg.colAddress1];
var addr2 = x[cfg.colAddress2];
var suburb = x[cfg.colSuburb];
var state = x[cfg.colState];
var postcode = x[cfg.colPostcode];
var country = x[cfg.colCountry];
var orderMsg = x[cfg.colOrderMessage];
var carrier = x[cfg.colCarrier];
var itemCode = x[cfg.colItemCode];
var itemQuantity = x[cfg.colItemQuantity];
var itemName = x[cfg.colItemName];
var itemPrice = x[cfg.colitemPrice];
var item = {};
item[cfg.colItemCode] = itemCode;
item[cfg.colItemQuantity] = itemQuantity;
item[cfg.colItemName] = itemName;
item[cfg.colItemPrice] = itemPrice;
var orderObj = {};
orderObj[cfg.colOrderId] = orderId;
orderObj[cfg.colAddressee] = addressee;
orderObj[cfg.colCompany] = company;
orderObj[cfg.colAddress1] = addr1;
orderObj[cfg.colAddress2] = addr2;
orderObj[cfg.colSuburb] = suburb;
orderObj[cfg.colState] = state;
orderObj[cfg.colPostcode] = postcode;
orderObj[cfg.colCountry] = country;
orderObj[cfg.colOrderMessage] = orderMsg;
orderObj[cfg.colCarrier] = carrier;
orderObj["Items"] = [ item ];
return orderObj;
}
});
return retVal;
}

Javascript module pattern with array

I have an exercise which i don´t really understand, so I hope for some help for this.
I should hardcode a simple array and the exercise tells me this:
Often, when we create our web applications, we have the need for test data. Implement a reusable nodejs module, using JavaScripts module pattern, which can provide random test data as sketched below:
var data = dataGenerator.getData(100,"fname, lname, street, city, zip");
This should return a JavaScript array (not JSON) with 100 test data on the form:
[{fname: "Bo", lname:"Hansen", street: "Lyngbyvej 26", city: "Lyngby", zip: "2800"},..]
If you call it like this:
var data = dataGenerator.getData(25,fname, lname);
it should return 25 test data as sketched below:
[{fname: "Bo", lname:"Hansen"},..]
I have some code here, but this dosen´t work yet:
var dataGenerator = (function () {
var data = [
{
fname : "Bo",
lname : "Bosen",
...
},
{
fname : "jashkjh",
lname : "jhsdkfj",
...
},
...
];
return {getData : function (count, fields) {
var result = [];
var i = 0;
var field;
var j;
fields = fields.split(/\s*,\s*/);
while (i < count && i < data.length) {
result.push({});
// Det objekt vi arbejder på lige nu er i result[i]
for (j = 0; j < fields.length; j++) {
result[i][fields[j]] = data[i][fields[j]];
}
i++;
}
return result;
}};
})();
module.exports = dataGenerator;
I do not know the data body, but could try:
var data=[{fname:"Bo",lname:"Bosen",street:"Lyngbyvej 26",city:"Lyngby",zip:"2800"},{fname:"jashkjh",lname:"jhsdkfj",street:"Fmsn 9",city:"Pra",zip:"1600"},{fname:"eeee",lname:"aaaa",street:"Eda 5",city:"Pre",zip:"3500"}];
var dataGenerator = {
getData: function(count, fieldsStr){
var result = [], fields = fieldsStr.split(/\s*,\s*/), i = 0;
while(i < count && data[i]){
var item = {};
fields.forEach(function(key){
item[key] = data[i][key]
});
result.push(item);
i++
}
return result
}
}
var results = dataGenerator.getData(2,"fname, zip");
document.write(JSON.stringify(results))

Get anchor tag values in jQuery

I have a html tag like this.
<a class="employee_details" target="_blank" href="index1.php?name=user1&id=123">User</a>
I need to get the two parameter values in jquery
<script type="text/javascript">
$(function () {
$('.employee_details').click(function () {
var status_id = $(this).attr('href').split('name');
alert(status_id[0]);
});
});
</script>
Any help in getting both the parameter values in two variables in javascript.
I want to get user1 and 123 in two variables using jQuery
Thanks
Kimz
You can use URLSearchParams as a most up-to-date and modern solution:
let href = $(this).attr('href');
let pars = new URLSearchParams(href.split("?")[1]);
console.log(pars.get('name'));
Supported in all modern browsers and no jQuery needed!
Original answer:
Try this logic:
var href = $(this).attr('href');
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
console.log(result);
So you'll get the parameters as properties on result object, like:
var name = result.name;
var id = result.id;
Fiddle.
An implemented version:
var getParams = function(href)
{
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
return result;
};
$('.employee_details').on('click', function (e) {
var params = getParams($(this).attr("href"));
console.log(params);
e.preventDefault();
return false;
});
Fiddle.
$(function() {
$('.employee_details').on("click",function(e) {
e.preventDefault(); // prevents default action
var status_id = $(this).attr('href');
var reg = /name=(\w+).id=(\w+)/g;
console.log(reg.exec(status_id)); // returns ["name=user1&id=123", "user1", "123"]
});
});
// [0] returns `name=user1&id=123`
// [1] returns `user1`
// [2] returns `123`
JSFiddle
NOTE: Better to use ON method instead of click
Not the most cross browser solution, but probably one of the shortest:
$('.employee_details').click(function() {
var params = this.href.split('?').pop().split(/\?|&/).reduce(function(prev, curr) {
var p = curr.split('=');
prev[p[0]] = p[1];
return prev;
}, {});
console.log(params);
});
Output:
Object {name: "user1", id: "123"}
If you need IE7-8 support this solution will not work, as there is not Array.reduce.
$(function () {
$('.employee_details').click(function () {
var query = $(this).attr('href').split('?')[1];
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
var varName = decodeURIComponent(pair[0]);
var varValue = decodeURIComponent(pair[1]);
if (varName == "name") {
alert("name = " + varValue);
} else if (varName == "id") {
alert("id = " + varValue);
}
}
});
});
It's not very elegant, but here it is!
var results = new Array();
var ref_array = $(".employee_details").attr("href").split('?');
if(ref_array && ref_array.length > 1) {
var query_array = ref_array[1].split('&');
if(query_array && query_array.length > 0) {
for(var i = 0;i < query_array.length; i++) {
results.push(query_array[i].split('=')[1]);
}
}
}
In results has the values. This should work for other kinds of url querys.
It's so simple
// function to parse url string
function getParam(url) {
var vars = [],hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// your code
$(function () {
$('.employee_details').click(function (e) {
e.preventDefault();
var qs = getParam($(this).attr('href'));
alert(qs["name"]);// user1
var status_id = $(this).attr('href').split('name');
});
});

Categories