Axios get one parameter with multiple values separated by comma - javascript

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"

Related

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.

Accessing multiple parameter values in Google Apps Script

From this article from Martin Hawksey, summarized:
a script bound to the Sheet is published as a web app, a form uses jQuery's $.ajax to send the request to that web app, and the web app handles the parameters into columns of the Sheet with headers matching the names of each param. (the script in this article makes use of PublicLock, which I've changed to ScriptLock)
My problem revolves around checkboxes. Inside the request, I'll see
...fruit=apple&fruit=banana&fruit=cantaloupe...
and the Apps Script will see this as well, passing e to a function handleResponse() which is triggered from doPost(e). To access the values for the parameters in the request, we use e.parameter or e.parameters. I've chosen the latter to accommodate for checkboxes and multiple values for that particular parameter.
What's not happening, though, is exactly that: only the first checkbox value is being sent through. To iterate through params, we use
for (i in headers) {
if (headers[i] == "Timestamp") {
row.push(new Date());
} else {
row.push( e.parameters[headers[i]] );
}
}
to push the values for each parameter that matches a column header into a new array that will be entered as a new row. To do that, Hawksey uses
sheet.getRange(nextRow, 1, 1, row.length).setValues([row])
I guess I'm having trouble understanding what e.parameters does and how I can access the those values. I understand that the parameters property houses the values of each name as arrays, but I can't get an array's entire list of elements to be the value for a cell in a row. Can someone help me understand what e.parameters does, and how I can better get to all of the values I need?
e.parameters is an object where the parameters are the object keys and the values are stored in an array. So, a request like this:
url?fruit=apple&fruit=orange&fruit=lime&animal=giraffe
would yield an object like this:
{'fruit': ['apple', 'orange', 'lime'], 'animal': ['giraffe']}
If you have to put all values for fruit into one cell, you might try:
e.parameters.fruit.join(',')
which will return a string with each value separated by a comma. Then, if you need to separate the values again, you could use String.split() (docs here).

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.

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

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/.

How to compare Two data stores in Dojo

I have two data store of type dojo.data.ItemFileReadStore.One of the data store having old data and other one having new data.How can i compare these two data stores?
I call the fetch method on both of the stores and did a compare but didn't work for me.
IF a same item can be in two stores, then you could fetch all items from one store, on Complete, foreach item, otherStore.isItem(someItem) which will return a boolean :)
Have you tried that?
The format used by ItemFileReadStore is not a requirement of the dojo.data API. The
format it uses is designed to work well for the specific situations
ItemFileReadStore is used for, which are moderately sized data sets that can be easily
represented in a JavaScript Object tree.
Structure of Input Data Format
{
"label": "some attribute", // Optional attribute used to indicate which attribute on
an item should act as a human-readable label for display purposes.
"identifier": "some attribute", // Optional attribute used to indicate which
attribute on an item acts as a unique identifier for that item. If it is not defined,
then the ItemFileReadStore will simply number the items and use that number as a
unique index to the item.
"items:" [ // The array of JavaScript objects that act as the root items of the data
store
{ /* Some set of name/value attributes */ },
{ /* ... */ },
...
]
}
solution 1: in our application we have used this method:
dojo.require("dojo.json");
_equal: function(objA, objB) {
return dojo.json.stringify(objA) === dojo.json.stringify(objB);
}
the data inside objects should also have the same order, otherwise comparison will fail.
solution 2: but in dojo 1.8 they have introduced dojox/mvc/equals function.
it compares two given objects.
please also consider using dojo/store instead of deprecated dojo/data

Categories

Resources