Query String generated by $.param() include square brackets for array - javascript

I have an object like this:
var queryObject= {
name: 'Shwetanka',
subjects: ['Mathematics', 'Physics', 'Computers'],
stream: 'science'
};
When I create query string with this using $.param(queryObject) I get this as query string:
name=Shwetanka&subjects%5B%5D=Mathematics&subjects%5B%5D=Physics&subjects%5B%5D=Computers&stream=science
Expected: name=Shwetanka&subjects=Mathematics&subjects=Physics&subjects=Computers&stream=science
How do avoid [] added by the method in the query string for params with same name. In the backend I'm using struts2 to read params.

I've found the solution. I just have to pass 'traditional=true' in $.param(queryObject, true). This generates the query string i want.

When we have fields with same name in a form and it is submitted via GET/POST, it is bound to be send as an array of params with the same name.
And the server would be expecting the values as such. So, Even if you somehow remove that [], it ceases to be an array, and the server will get only one value.
jQuery param method is designed, with the same thing in mind.
Check out examples in http://api.jquery.com/jQuery.param/.

Related

Axios get one parameter with multiple values separated by comma

I have a table in React with data about tests which I get from API. I have to do filters on frontend and be able to join them, for example filter tests from chosen category, chosen difficulty and created before some data.
If I wanted to filter for example tests from category "Javascript" and difficulty "Junior", I should get the uri:
/api/admin/filters?filter=category:Javascript,difficulty:JUNIOR
If I wanted to filter tests for "Junior" or "Mid" I should get:
/api/admin/filters?filter=difficulty:JUNIOR,difficulty:'MID
Note apostrophe here which stands for "or".
I should also be able to filter by creation date, for example:
/api/admin/filters?filter=creationDate<2019-09-23 17:34:21,creationDate>2019-09-12 17:34:21
I wonder how I can create such queries? URLSearchParams or axios params adds parameters separated by & so I can't use it here because I have one parameter "filter" with multiple values. Or maybe I should use it and also use js replace method for replacing & for comma? I have also no idea how to add apostrophe.
I saw similar question here: https://spectrum.chat/react/general/query-string-sending-multiple-value-to-the-same-parameter~5d029da0-e7da-443d-a4b2-1529ca7b4f82
but I can't use an array in my case because I have multiple filters. I suppose I have to create object like:
options = {
difficulty: [junior, mid],
category: [javascript],
created before: 2019-09-23 17:34:21,
created after: 2019-09-12 17:34:21
}
and now how to add keys and values from such object to uri so it looks like backend expects?
Any help would be appreciated.
Encoding parameters with encodeURI before passing to axios might solve your issue.
If you need to pass parameters with special characters (like '[',']' ...etc) you should give the parameter as a string '["junior","mid"]' instead of giving parameter as an array.
(Giving as an array will just remove the brackets)
var params = '["junior","mid"]'
encodeURI(params) // it returns "%5B%22junior%22,%22mid%22%5D"
var params = ["junior","mid"]
encodeURI(params) // it returns "junior,mid"

MongoDB array turned into string on database

I have problem with Mongo/express array parsing. A array from body seems to be correct when I console.log response in node console. But the problem is when I try to save the body to mongo.db using insert.one method, the post is saved but the array turns into string, which is bad for me.
This is what I'm sending to mongo (the data is ok, i console.log it, array is not string here)
{
createdBy: this.userName,
postContent: this.post,
tags: this.tags,
addedAt: new Date()
};
And this is what is stored in database
Update:
When I hardcode array into payload it's showed correctly as an array in mongo.
But of course problem still exist for dynamic data
You should be able to use JSON parse along with a replace to force it to accept the string as an array, like this:
const array = JSON.parse(this.tags.replace(/'/g, '"'));
Then set tags to the value of array:
tags: array
Use data type as array -- 4 and use .pretty().
Generally if you use find() method returns data in a dense format.
By using cursor.pretty() you can set the cursor to return data in a format that is easier for humans to parse

Form a string in typescript with all attendees in Google Calendar API

I am trying to create an event using Google Calendar API using HTTP method.I am writing all my code in typescript.
Now, I have an array containing the email ids of all the attendees that we want to add to that event. So, to pass all those email ids of the attendees in a single query parameter, I am trying to form a single string in the exact format as that shown in API docs. But after forming the string, when I make the API request from server side code, it somehow passes unwanted backslash in that string.
I have tried forming a string by concatenating the keyword email which is to be sent in front of every email that I want to include as attendee. I tried using single backslash () as an escape sequence to insert double-inverted commas, but it didnt work.
I have also tried doing the same thing using join() function, but still unwanted backslashes get introduced in the string when I passed it as attendee parameter value in Create Event API call.
The expected format of string I need to pass in the API call is :
"attendees": [
{
"email": "xyz#gmail.com"
},
{
"email" : "abc#gmail.com"
}
]
The function I am trying to form the string is -
for (let index = 0; index < email_ids.length-1; index++) {
mapping = mapping + "{'email':"+"'"+email_ids[index]+"'}";
if((email_ids.length-1)!=index) {
mapping=mapping+ ",";
}
}
Here mapping is the string I am trying to form.
Now the problem is when I console.log this mapping string, it prints something like -
{'email': " xyz#gmail.com '} , {'email': " abc#gmail.com '}
which is exactly something I want to pass inside the attendee parameter. But when I read the logs of the API request that I sent, I see the parameter attendee to be something like -
"attendees":["{\'email\': \\" xyz#gmail.com \'} , {\'email\': \\" abc#gmail.com \'} "]
There are these unwanted backslashes that get introduced at every point of concatenation in my above function, and I want to remove these. I think this is the reason why I am creating a public event but it isn't adding the attendees to that event, so this adding attendees part is not working as expected.
Any help is appreciated. Thanks a lot in advance.
You seem to be generating a string, and passing this back to whatever method is sending the data. Like Dan D said in a comment, try creating an object instead, as it seems that's what the interface is expecting in the atendees[] field.
This also simplifies your code a lot:
const list = email_ids.map((id: string) => ({ email: id }));
This creates a full list. In on your code you skip the last item in email_ids. I'm assuming it's an error, but if not, you can do it this way:
const list = email_ids
.filter((_:string, i:number)=> i < email_ids.length -1)
.map((id: string) => ({ email: id }));
This will generate an Array with the objects, as in
[
{ email: "xyz#gmail.com" },
{ email: "abc#gmail.com" }
]
Also, notice your code seems to be transforming the data into an array somewhere already:
"attendees":["..."]
So to avoid an array inside of an array, you'll need to figure out what's going on and how to pass/receive the correct data. It's hard to say without looking at the whole lifecycle of that payload from generation to sending to the server.
Lastly: in general, there's no reason to generate JSON by hand. In fact, I can't think of a single reason where anyone would ever want or need to create a JSON source code directly. If you really need a string rather than ab object, creating an object (like above) and calling JSON.stringify() on it later is the right solution.

Getting string index value from Javascript to MVC C# Controller using string[] array as a parameter

I am new in this environment and i just want to ask somebody if it is possible to get the string value not the index value using string[] array as a parameter?
Below are those images: ajax pass this data into controller
I am using ajax to pass my data in to the url controller in c# mvc.
By the way, here's my sample array data: prepared data..
the highlighted one is my array and in my parameter in mvc # is declared as string [] methodParam: highlighted parameter,
Those not highlighted parameter are working. all i want to do is getting one by one string in methodParam. i tried to use this
GetMethodParam.IndexOf("Date").ToString() but the output is -1 which probably not available in context.
i just want to get each string and its value because i send it to the email outlook..
like this. enter image description here.
Any Suggestions, clarification or comments is highly appreciated. Thank you ;) .
You don't need the individual input in data on ajax call, just use the last one UserHeader
and in Acton(C#) use a model as argument with containing all attributes of UserHeader.
Or, remove UserHeader from data and Use each attributes as individual argument in C# Action with same name.

javascript array into object with same key names

I have an unusual problem to solve here. I have an array of Guids
[
"c01f8237-72c8-4fa6-9c53-1915750385aa",
"2c8a471b-c408-436c-81b1-3f3867d8ffb4",
"27a44d46-12bd-4784-ceed-57ada31b0e33"
]
This array has to be transformed into:
{
id: "c01f8237-72c8-4fa6-9c53-1915750385aa",
id: "2c8a471b-c408-436c-81b1-3f3867d8ffb4",
id: "27a44d46-12bd-4784-ceed-57ada31b0e33"
}
I know that shouldn't be done, but unfortunately cannot control the back end part. Any idea?
Thanks
The whole point of a dictionary key is that it uniquely maps to some value. Your desired output attempts to duplicate a key and therefore is neither possible nor does it make sense.
If you're passing this to a backend (as you suggest), then of course you can manually build a string to pass over the wire that duplicates keys in the payload, but you won't be able to actually do it in JavaScript first. You'll have to manually build the string.
Also note that you can call this format whatever you want, but you can't call it JSON and you can't use JSON libraries to build it (because it's not JSON). If your API expects a custom format, then you need to write code to build that custom format.
If all you want is a string just do something like
var str = '{' + idArray.map(function(id) {
return "id: "+id
}).join(',\n')+'}';
I have no idea what mime type you would put on that though since its not valid JSON.

Categories

Resources