Adding parameters to URL, putting array in query string - javascript

Objective
I've built an interactive where people can choose six players to make their all-star team. When they click share to Twitter, my hope is to have a URL containing parameters of all six players something like website.com/?playerName=picked?playerName=picked so that people can share their teams
Question
What is the best way to append parameters to a URL?
How do you put an array into a query string?

You can use an array directly in a url, however you would need to serialize the array into a string. like this player[]=one&player[]=two
here is a little function to automate it.
when using url's you should always use encodeURIComponent to encode any non url friendly characters. The players are an array so we map over it and get a new array that has been encoded.
After that we simply need to join the array with &
const players = [
'player Name 1',
'playerName2',
'playerName3'
]
const parameterizeArray = (key, arr) => {
arr = arr.map(encodeURIComponent)
return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}
console.log(parameterizeArray('player', players))
edit
The only difference is the function declaration style, everything else is standard ES5
function parameterizeArray(key, arr) {
arr = arr.map(encodeURIComponent)
return '?'+key+'[]=' + arr.join('&'+key+'[]=')
}

Cleaner:
website.com/?players=player1,player2,player3,player4
Then split the query to get result:
var arrayResult = query.players.split(",")

Related

what are the ways to convert a simple array to 'nested array in javascript?

I want to capture screenshots on my remote virtual machine without using display. I came across a library in nodejs 'capture screenshot' (https://github.com/sindresorhus/capture-website) which is pretty straightforward.
Taking screenshot of a single link is fairly simple, however taking multiple screenshots becomes tricky. I don't want to put links manually as it will be time consuming. I am running a script to get all anchor tags in python and saving a csv file of links gathered. This is how it looks when I convert the saved csv file to a JavaScript array.
[ 'https://www.google.com/imghp?hl=en&tab=wi',
'https://maps.google.com/maps?hl=en&tab=wl',
'https://play.google.com/?hl=en&tab=w8',
'https://www.youtube.com/?gl=US&tab=w1',
'https://news.google.com/nwshp?hl=en&tab=wn',
'https://mail.google.com/mail/?tab=wm',
'https://drive.google.com/?tab=wo',
'https://www.google.com/intl/en/about/products?tab=wh',
'https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/',
'https://www.google.com/url?q=https://lifeinaday.youtube/%3Futm_source%3Dgoogle%26utm_medium%3Dhppcta%26utm_campaign%3D2020&source=hpp&id=19019062&ct=3&usg=AFQjCNEJMAD58Mjdnro8Mjm-RtJ3nfEIZA&sa=X&ved=0ahUKEwi98PWM4-HqAhVh1uAKHeYGCPwQ8IcBCAU'
]
I want to convert the above array to the array shown below.
[
['https://www.google.com/imghp?hl=en&tab=wi', 'anyanme'],
['https://maps.google.com/maps?hl=en&tab=wl','anyanme'],
['https://play.google.com/?hl=en&tab=w8','anyanme'],
['https://www.youtube.com/?gl=US&tab=w1','anyanme'],
['https://news.google.com/nwshp?hl=en&tab=wn','anyanme'],
['https://mail.google.com/mail/?tab=wm','anyanme'],
['https://drive.google.com/?tab=wo','anyanme'],
['https://www.google.com/intl/en/about/products?tab=wh','anyanme'],
['https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/','anyanme'],
['https://www.google.com/url?q=https://lifeinaday.youtube/%3Futm_source%3Dgoogle%26utm_medium%3Dhppcta%26utm_campaign%3D2020&source=hpp&id=19019062&ct=3&usg=AFQjCNEJMAD58Mjdnro8Mjm-RtJ3nfEIZA&sa=X&ved=0ahUKEwi98PWM4-HqAhVh1uAKHeYGCPwQ8IcBCAU','anyanme']
];
``
I am newbie to javscript and having a hard time to solve this. Any help will be appreciated.
It looks like the library you're using wants an array of pairs, with a URL and a file name.
I would map your original array to the array of pairs, but you'll have to figure out what you want to do for file names.
Assuming you have a function, named toFileName that will take a URL string and return a file name that you want for that URL, you could map the original array into the array of pairs like this:
const pairArr = originalArray.map((url) => {
const fileName = toFileName(url);
return [url, fileName];
});
If you just want to try to use the URL as the filename, you could just do this:
const pairArr = originalArray.map((url) => {
return [url, url];
});
This will be an issue with most URLs, though, as they'll have characters that are invalid for filenames. If you need a file extension with this approach, you could use string concatenation (url + '.png') for the second item in the returned pair.
You ca achieve it with a Map and regex
const arr = ['https://www.google.com/imghp?hl=en&tab=wi',
'https://maps.google.com/maps?hl=en&tab=wl',
'https://play.google.com/?hl=en&tab=w8',
'https://www.youtube.com/?gl=US&tab=w1',
'https://news.google.com/nwshp?hl=en&tab=wn',
'https://mail.google.com/mail/?tab=wm',
'https://drive.google.com/?tab=wo',
'https://www.google.com/intl/en/about/products?tab=wh',
'https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/',
'https://www.google.com/url?q=https://lifeinaday.youtube/%3Futm_source%3Dgoogle%26utm_medium%3Dhppcta%26utm_campaign%3D2020&source=hpp&id=19019062&ct=3&usg=AFQjCNEJMAD58Mjdnro8Mjm-RtJ3nfEIZA&sa=X&ved=0ahUKEwi98PWM4-HqAhVh1uAKHeYGCPwQ8IcBCAU',
'',
];
function extractName(str) {
const regex = /https:\/\/(.*?)\//g;
const ret = regex.exec(str);
return (ret && ret[1]) || null;
}
const items = arr.map(x => [
x,
extractName(x),
]);
console.log(items);

Output capitalized names from randomUser.me api?

Forgive me if this isn't the right platform to ask this question. And let me preface that I'm a designer with very little API and javascript experience.
I'm using the randomUser api to generate a json file or url I can input in Invision's Craft tool for Sketch, so I can input real data in my designs. https://screencast.com/t/jAkwUpUja2. However, it gives the names in lowercase instead of title-case/capitalized.
I'm generating the JSON by typing the endpoints I need in the browser: https://screencast.com/t/E8Cmjk5XSSCk
So, is there a way I can force the api to give me capitalized names? Thanks!
EDIT: here is the JSON url: https://randomuser.me/api/?results=20&nat=us&inc=name,gender,picture&format=pretty
Here is the simplest way to capitalize a string with JS, as far as i know:
// let's assume, that you have stored the lastname as follow:
let last = 'rodney';
To transform the lastname, you apply this pattern:
let capitalizedLast = last[0].toUpperCase() + last.substr(1);
last[0] returns the first letter of the string r.
last.substr(1) gives the rest of the lastname odney
with toUpperCase() you transform the first letter and + will concatenate both to the final result.
You just need to itterate over the results from your API and transform the elements that you needed in that way.
A quick look at the documentation suggests that there might not be a way to get the API to return capitalized names directly. So you're going to have to write some JavaScript to do the job for you.
This code should print out the data to the console with all names capitalized.
It iterates through the items in the result array, goes through all properties of the item's name property and capitalizes them.
The capitalize function gets the first character of the name, converts it to upper case and appends it to the rest of the name.
function capitalize(text) {
return (!text || !text.length) ?
text :
(text[0].toUpperCase() + text.slice(1));
}
$.get("https://randomuser.me/api/?results=20&nat=us&inc=name,gender,picture&format=pretty",
function(data) {
if (!data || !data.results)
return;
data.results.forEach(function(user) {
if (user.name) {
for (var name in user.name) {
user.name[name] = capitalize(user.name[name]);
}
}
});
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How can I create a URL encoded query string from an array of objects?

I found tons of examples of how to turn an objects keys/values into a URL encoded query string, but I need to use an array of objects and turn them into a query string.
I want to use pure JS or lodash to accomplish this task.
I am supplying an array of objects in this format:
[
{ points: "30.09404881287048,-96.064453125" },
{ points: "30.09404881287048,-94.63485717773439" },
{ points: "29.345072482286373,-96.064453125" },
{ points: "29.345072482286373,-94.63485717773439"}
]
I need it to be in this format:
points=30.09404881287048%2C-96.064453125&points=30.09404881287048%2C-94.63485717773439&points=29.345072482286373%2C-96.064453125&points=29.345072482286373%2C-94.63485717773439
I am currently accomplishing this using these two methods:
import { map as _map } from 'lodash';
const createQueryStringFromObject = object =>
_map(object, (value, key) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
const createQueryStringFromArray = array => array.reduce((queryString, object, index) => {
return queryString + createQueryStringFromObject(object) + (index < array.length - 1 ? '&' : '');
}, '');
I find the reduce function implementation sloppy though and I think it could be cleaner and more efficient. Any suggestions?
EDIT: I would like to keep the method generic so it can accept an array of objects with any key and not just specifically the key points. I also would like to keep the createQueryStringFromObject() method because I need it elsewhere on the site.
I like your solution, but I think just using built in prototype methods will clean up the code quite a bit:
list.map(p => `points=${encodeURIComponent(p.points)}`).join('&')
which results in
"points=30.09404881287048%2C-96.064453125&points=30.09404881287048%2C-94.63485717773439&points=29.345072482286373%2C-96.064453125&points=29.345072482286373%2C-94.63485717773439"
I am looking for a generic implementation that is not specific to any objects containing the key of points. Thanks to melpomene's suggestion to just use another map and join, I gave that a shot and I definitely like that format alot more. Much shorter and clear!
const createQueryStringFromArray = array =>
_map(array, object => createQueryStringFromObject(object))
.join('&');

Is there a better way to check a string against the names of arrays?

I am currently trying to create a function that given the string of one variable to return the results of an array with the same name, with the intent to use this to return only the twitter profiles that are needed.
For example, if the variable profile is equal to ManUtd, then return the array ManUtd and its contents.
The array ManUtd will contain all the players on twitter who play for that club which can then be used to return only those twitter profiles.
so far my initial thought is to do something such as:
var ManUtd = [
// array containing all ManUtd twitter players
]
function checkTeam(profile){
if ( profile == ManUtd ){
// use the array ManUtd
} else if {
// the rest of the possible results
}
This isn't very efficient and seems rather verbose a solution. Is there a better way to achieve these results?
Don't make global variables called, eg, ManUtd. Instead make an object that contains keys and the values you want:
var teams = {
'ManUtd': [the array you mentioned],
'Arsenal': [some other array],
//etc
};
Then get the arrays like this:
function checkTeam(profile){
if (teams[profile]) {
return teams[profile];
}
}
Yes, there is a better way. Use a dictionary. Store all your array in the dictionary, and retrieve the right one later with the key.
See https://docs.python.org/3.5/library/stdtypes.html?highlight=dictionary#mapping-types-dict

producing a word from a string in javascript

I have a string which is name=noazet difficulty=easy and I want to produce the two words noazet and easy. How can I do this in JavaScript?
I tried var s = word.split("=");
but it doesn't give me what I want .
In this case, you can do it with that split:
var s = "name=noazet difficulty=easy";
var arr = s.split('=');
var name = arr[0]; //= "name"
var easy = arr[2]; //= "easy"
here, s.split('=') returns an array:
["name","noazet difficulty","easy"]
you can try following code:
word.split(' ').map(function(part){return part.split('=')[1];});
it will return an array of two elements, first of which is name ("noazet") and second is difficulty ("easy"):
["noazet", "easy"]
word.split("=") will give you an array of strings which are created by cutting the input along the "=" character, in your case:
results = [name,noazet,difficulty,easy]
if you want to access noazet and easy, these are indices 1 and 3, ie.
results[1] //which is "noazet"
(EDIT: if you have a space in your input, as it just appeared in your edit, then you need to split by an empty string first - " ")
Based on your data structure, I'd expect the desired data to be always available in the odd numbered indices - but first of all I'd advise using a different data representation. Where is this string word coming from, user input?
Just as an aside, a better idea than making an array out of your input might be to map it into an object. For example:
var s = "name=noazet difficulty=easy";
var obj = s.split(" ").reduce(function(c,n) {
var a = n.split("=");
c[a[0]] = a[1];
return c;
}, {});
This will give you an object that looks like this:
{
name: "noazert",
difficulty: "easy"
}
Which makes getting the right values really easy:
var difficulty = obj.difficulty; // or obj["difficulty"];
And this is more robust since you don't need to hard code array indexes or worry about what happens if you set an input string where the keys are reversed, for example:
var s = "difficulty=easy name=noazet";
Will produce an equivalent object, but would break your code if you hard coded array indexes.
You may be able to get away with splitting it twice: first on spaces, then on equals signs. This would be one way to do that:
function parsePairs(s) {
return s.split(' ').reduce(
function (dict, pair) {
var parts = pair.split('=');
dict[parts[0]] = parts.slice(1).join('=');
return dict;
},
{}
);
}
This gets you an object with keys equal to the first part of each pair (before the =), and values equal to the second part of each pair (after the =). If a string has multiple equal signs, only the first one is used to obtain the key; the rest become part of the value. For your example, it returns {"name":"noazet", "difficulty":"hard"}. From there, getting the values is easy.
The magic happens in the Array.prototype.reduce callback. We've used String.prototype.split to get each name=value pair already, so we split that on equal signs. The first string from the split becomes the key, and then we join the rest of the parts with an = sign. That way, everything after the first = gets included in the value; if we didn't do that, then an = in the value would get cut off, as would everything after it.
Depending on the browsers you need to support, you may have to polyfill Array.prototype.reduce, but polyfills for that are everywhere.

Categories

Resources