Remove brackets from url with array of ids (Request.js)

I have an application with nodejs express who makes request but when I pass an array I am:

Example: /foo?id=1&id=3&id=5

How to remove '[]' ?

var requestQueryParams = {id: [1,3,5]}

var options = {
        url: 'www.test.com',
        headers: {'content-type': 'application/json', 'accept': 'application/json'},
        qs: requestQueryParams || {}
    };

request.get(options), function(){...}

result: www.test.com?id[0]=1&id[1]=3&id[2]=5

Request.js = https://www.npmjs.org/package/request

Qs.js = https://www.npmjs.org/package/qs

Qs.stringify({ a: ['b', 'c', 'd'] }); // 'a[0]=b&a[1]=c&a[2]=d'

javascript, Since some time now there is a better solution. request uses qs per default to stringify the passed in qs object which also accepts options for formatting it. One of  the most simple solution for removing the brackets is, 1.convert the arraylist into string with .toString () method. 2.use String.substring (1,strLen-1). (where strLen is the length of string after conversion from arraylist). 3.Hurraaah..the result string is your string with removed brackets.

What do you want instead? If you want www.test.com?id0=1&id1=3&id2=5, then you need to give it a params object like this:

var requestQueryParams = { id0: 1, id1: 3, id2: 5 }

If you already have an object that looks like { id: [1,2,3] }, then you need to convert that object into one like the above. You can do that in a for loop easily enough:

var requestQueryParams = { id: [1,3,5] },
    newRequestQueryParams = {};

for(var i = 0; i < requestQueryParams.id.length; i++) {
  var paramName = "id" + i, // "id0", "id1", etc.
      id = requestQueryParams.id[i];

  newRequestQueryParams[paramName] = id;
}

console.log(newRequestQueryParams);
// => { id0: 1, id1: 3, id2: 5 }

Update: If you want a query string like id=1&id=3&id=5 (although this would be very strange, as I mention in my comment below), you can also do it in a for loop, as above, or you could do something like this:

var requestQueryParams = { id: [1,3,5] },
    queryStringParts = [], // an array this time
    queryString;

for(var i = 0; i < requestQueryParams.id.length; i++) {
  var param = "id=" + parseInt( requestQueryParams.id[i] );
  queryStringParts.push(param);
}
// queryStringParts is now [ "id=1", "id=3", "id=5" ]

queryString = queryStringParts.join("&")
console.log(queryString);
// => "id=1&id=3&id=5"

I used parseInt inside the for loop because I'm assuming the IDs are coming from an untrusted source (e.g. a user) and, since you're building a string manually instead of using a library that will encode the data for you, you want to prevent a malicious user from injecting arbitrary strings into your request. You could also use encodeURIComponent, but it's overkill if IDs should always be numbers.

How to remove square bracket and double quotes from extracted , I have one json array object and i need to extract one particular value out of it i need to remove this square bracket and double quotes and i want value as vIMS. I need to extract the value of id which is vIMS and i could extract the value In some scenarios, we can avoid JS and use Message Templates  How to add a parameter to the URL in JavaScript ? Given a URL and the task is to add an additional parameter (name & value) to the URL using JavaScript. URL.searchParams: This readonly property of the URL interface returns a URLSearchParams object providing access to the GET decoded query arguments in the URL.

My Solution is override (request.Request.prototype.qs)

var qs = require('qs'),
request = require('request'),
url = require('url');

var stringify;
var toString = Object.prototype.toString;

var isArray = Array.isArray || function (arr) {
return toString.call(arr) === '[object Array]';
};

var objectKeys = Object.keys || function (obj) {
var ret = [];
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        ret.push(key);
    }
}
return ret;
};

var stringifyString = function (str, prefix) {
if (!prefix) throw new TypeError('stringify expects an object');
return prefix + '=' + encodeURIComponent(str);
};

var stringifyArray = function (arr, prefix) {
var ret = [];
if (!prefix) throw new TypeError('stringify expects an object');
for (var i = 0; i < arr.length; i++) {
    ret.push(stringify(arr[i], prefix));
}
return ret.join('&');
};

function stringifyObject(obj, prefix) {
var ret = [];
var keys = objectKeys(obj);
var key;

for (var i = 0, len = keys.length; i < len; ++i) {

    key = keys[i];

    if ('' === key) {
        continue;
    }

    if (null === obj[key]) {
        ret.push(encodeURIComponent(key) + '=');

    } else {
        ret.push(stringify(obj[key], prefix ? prefix + '[' + encodeURIComponent(key) + ']' :     encodeURIComponent(key)));
    }
}

return ret.join('&');
}

stringify = function (obj, prefix) {
if (isArray(obj)) {
    return stringifyArray(obj, prefix);
} else if ('[object Object]' === toString.call(obj)) {
    return stringifyObject(obj, prefix);
} else if ('string' === typeof obj) {
    return stringifyString(obj, prefix);
} else {
    return prefix + '=' + encodeURIComponent(String(obj));
}
};

And override prototype.qs :

request.Request.prototype.qs = function (q, clobber) {
var base;

if (!clobber && this.uri.query) {
    base = qs.parse(this.uri.query)
}
else {
    base = {}
}

for (var i in q) {
    base[i] = q[i]
}

if (stringify(base) === '') {
    return this
}

this.uri = url.parse(this.uri.href.split('?')[0] + '?' + stringify(base));
this.url = this.uri;
this.path = this.uri.path;

return this;
};

How to send array as parameter in API Call??, i need to send array and other key value data in API call. so how can i call api? expects it, then all you have to do is put the body in a variable (eg: $json), then use Insert From URL to send the request. UpvoteUpvotedRemove Upvote Note the square brackets as the 'thing' to add to (first parameter). @@ -178,49 +178,89 @@ public function initialize_classes() {public function register_assets {: wp_register_script ( 'tournament_brackets_jquery_bracket', TOURNAMENT

Providing an array as a param isn't working as expected. · Issue , I want to put in the following get request using axios config.params object: //​front-end axios.delete(url, {paramsSerializer: accountsInfo } My back-end environment is node and koa2 , for GET method, I can get params like:. By Alessandro Artoni. As web developers, we have all tried many different tools, IDE’s and text editors to improve our daily workflow. Apart from the old-fashioned vim/emacs lover, many of us currently use either Sublime Text (with its great collection of plugins) or WebStorm.

query-string, Parse and stringify URL query strings. const queryString = require('query-string'​); 'bracket' : Parse arrays with bracket representation:. JavaScript remove round brackets - Laserfiche Answers. Press Ctrl + C to copy the link. ZoomRatio. Fit window. Fit width. 50%. 75%. 100%. 125%.

Express 4.x - API Reference, The function determines the file to serve by combining req.url with the For example, req.body.trim() may fail in multiple ways, for example stacking Routes HTTP DELETE requests to the specified path with the specified To route methods that translate to invalid JavaScript variable names, use the bracket notation. How do I remove the brackets from an ArrayList. This is my code. I need a loop that returns a string for my getBuiltInDevices. This code shown below is from one of my subclasses. I was supposed to add builtInDevices, which I did in my stockMain class.

Comments
  • I want to have the index.
  • Where do you want to "have the index"? I see you edited your question, which has unfortunately made it less clear. Is id=1&id=3&id=5 the query string you want to end up with? Since it's a very non-standard format (with duplicate parameters most endpoints will take only the last, i.e. id=1 and id=3 will be ignored in favor of id=5), so you'll probably have to just build the string manually. I'll update my answer to show how you might do that.
  • @JordanRunning: Passing multiple parameters with the same name is the standard way of passing a list of values. Both in the query string and in POST data. Every web framework ought to support getting all the values.
  • That’s interesting, Matti. Can you give me a link to the standard?