How to iterate over array to build a url? - javascript

I'm trying to fetch data based on the url.
Everything works except on: let urlFilters.
What I'm trying to do:
iterate over the array: filters (if it's not null)
save output in: let urlFilters
By now, the iteration seem to work. When I console.log(urlFilters) I get key-value-pairs like "filter=orange" or "filter=apple?". The problem: only the last key-value-pair is saved and thus used for the url.
My question: how can I save all the key-value-pairs from the iteration and use them all in the url?
const getInfo = async(filters, searchTerm) => {
let url = "";
let urlBasis = "/api/productInfo?";
let urlSearchTerm = "";
let urlFilters = "";
if (searchTerm.length !== 0) {
...
} else {
...
};
//problem
if (filters.length !== 0) {
filters.forEach((filterItem, index) => {
urlFilters = `filter=${filterItem.categoryUrl}${index === filters.length -1 ? "" : "&"}`
//console.log(urlFilters) -> "filter=orange" or "filter=apple&"
});
} else {
urlFilters = ""
};
try {
//problem urlFilters: shows only the last key-value pair
url = urlBasis + urlSearchTerm + `${searchTerm.length !== 0 && filters.length !== 0 ? "&" : ""}` + urlFilters
} catch (err) {
console.log(err);
}
};
I already tried to use .map instead of .forEach. I also tried to use the spread operator. But it didn't work and I'm a little stuck. Any suggestions (also for code improvement) are appreciated. Thanks a lot!

If I understand the question correctly, you can iterate over your array easier via .map and then merge the array into a single string using .join():
const data = [{url: "apple"}, {url: "banana"}]
const url = `http://myurl.com?${data.map(item => `filter=${item.url}&`).join('').slice(0, -1)}`
console.log(url)
Note that .slice() ist needed to cut the last & character off the string.

So I think my previous approach wasn't the best.
It seems as the URLSearchParams-API is a simpler approach when working with urls and params - at least with this solution the code works and looks cleaner.
Here is what I have now:
const getInfo = async (filters, searchTerm) => {
let url = "/api/productInfo?";
let params = new URLSearchParams();
if(searchTerm.length !== 0) {
//logic
};
if(filters.length !== 0) {
filters.forEach((filterItem) => {
params.append("filter", filters.categoryUrl);
});
};
try {
url = url + params;
console.log("url", url);
...
}
}

Related

Merge and combine item into array based on property

I am trying to merge an object into an array. Based on the title of the object, if it already exists in the array I want to add the amount of the object into the existing amount.
For example:
let items = [{"title":"x","amount":1}, {"title":"y","amount":1}, {"title":"z","amount":1}];
let obj1 = {"title":"x","amount":2};
If obj1 is merged into items the expected output would be
[{"title":"x","amount":3}, {"title":"y","amount":1}, {"title":"z","amount":1}]
Here is the solution I've come up with so far, Its working but I feel like there has to be a more elegant solution out there.
mergeResponses(x){
var found = this.items.some(function (arr) {
return arr.title === x.title;
});
if(!found){
//item doesnt exist, add to array
this.items.push(x);
}else{
//item already exists, add amount to existing amount
let dupItem = this.items.find(function (y) {
return y.title == x.title;
});
dupItem.amount += x.amount;
}
}
Below is a direct translation of your requirements. It's slightly more elegant than your implementation in the sense that the lookup only needs to be performed once.
let items = [{"title":"x","amount":1}, {"title":"y","amount":1}, {"title":"z","amount":1}];
let item = {"title":"x","amount":2};
let existing = items.find(i => i.title === item.title);
if (existing) {
existing.amount += item.amount;
} else {
items.push(item);
}
console.log(items);
you can do like this also,I don't say that this the better way but this also one way to do this.
var xyz=items.find(function(item){
if(item.title==obj1.title)
return item;
});
if(xyz)
xyz.amount+=obj1.amount;
else
items.push(obj1);
you can do as :
var items = [{"title":"x","amount":1}, {"title":"y","amount":1}, {"title":"z","amount":1}];
var obj = {"title":"x","amount":3};
matches = _.filter(items, i => i.title === obj.title)
if (matches) {
_.forEach (
matches,
match => match.amount += obj.amount
)
} else {
items.push(obj)
}
console.log(JSON.stringify(items))

Returning True if matching value found in array

I feel like this should be easy but I've been running into problems finding a solution.
I have an array of file extensions:
var items = ["PDF", "XLS"]
I also have an array of file objects:
files = [{format: "TXT"},{format: "PDF"}]
I'd like a function where I can pass the array of file objects, and if any of the files have a format that is in the items array, it should return true.
Thank you in advance for the help.
function hasItemExtension() {
files.forEach(file => {
if(items.indexOf(file.format) != -1) {
return true;
}
}
};
I see that you're trying to break a forEach() with a return and apparently it can't be done according to this doc:
There is no way to stop or break a forEach() loop other than by
throwing an exception. If you need such behavior, the forEach() method
is the wrong tool. Use a plain loop or for...of instead....
I have worked out this little example where I set the boolean variable and modify it if there is a match:
var items = ['PDF', 'XLS'];
var files = [{ format: 'PDF' }, { format: 'XLS' }];
function hasItemExtension(items, files) {
let result = false;
files.forEach(function(file){
let f = file.format;
if (items.indexOf(f) !== -1){
result = true;
}
});
return result;
}
let sol = hasItemExtension(items, files);
console.log(sol);
Just use javascript's array.some() method
var items = ["PDF", "XLS"]
var files = [{format: "TXT"},{format: "PDF"}]
console.log(files.some(file => items.indexOf(file.format) > -1))

Get Facebook referal in Chrome extension [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 1 year ago.
I have a URL with some GET parameters as follows:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
I need to get the whole value of c. I tried to read the URL, but I got only m2. How do I do this using JavaScript?
JavaScript itself has nothing built in for handling query string parameters.
Code running in a (modern) browser can use the URL object (a Web API). URL is also implemented by Node.js:
// You can get url_string from window.location.href if you want to work with
// the URL of the current page
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5";
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
For older browsers (including Internet Explorer), you can use this polyfill.
You could also use one for URLSearchParams and extract the query string to pass to it with window.location.search.substring(1).
You could also use the code from the original version of this answer that predates URL. The above polyfill is robust and well tested and I strongly recommend it over this though.
You could access location.search, which would give you from the ? character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.
Then you can parse it with this:
function parse_query_string(query) {
var vars = query.split("&");
var query_string = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
var key = decodeURIComponent(pair.shift());
var value = decodeURIComponent(pair.join("="));
// If first entry with this name
if (typeof query_string[key] === "undefined") {
query_string[key] = value;
// If second entry with this name
} else if (typeof query_string[key] === "string") {
var arr = [query_string[key], value];
query_string[key] = arr;
// If third or later entry with this name
} else {
query_string[key].push(value);
}
}
return query_string;
}
var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);
You can get the query string from the URL of the current page with:
var query = window.location.search.substring(1);
var qs = parse_query_string(query);
Most implementations I've seen miss out URL-decoding the names and the values.
Here's a general utility function that also does proper URL-decoding:
function getQueryParams(qs) {
qs = qs.split('+').join(' ');
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);
source
function gup( name, url ) {
if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
return results == null ? null : results[1];
}
gup('q', 'hxxp://example.com/?q=abc')
This is an easy way to check just one parameter:
Example URL:
http://myserver/action?myParam=2
Example Javascript:
var myParam = location.search.split('myParam=')[1]
if "myParam" exists in the URL... variable myParam will contain "2", otherwise it will be undefined.
Maybe you want a default value, in that case:
var myParam = location.search.split('myParam=')[1] ? location.search.split('myParam=')[1] : 'myDefaultValue';
Update: This works better:
var url = "http://www.example.com/index.php?myParam=384&login=admin"; // or window.location.href for current url
var captured = /myParam=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
var result = captured ? captured : 'myDefaultValue';
And it works right even when URL is full of parameters.
Browsers vendors have implemented a native way to do this via URL and URLSearchParams.
let url = new URL('http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('c')); // outputs "m2-m3-m4-m5"
Currently supported in Firefox, Opera, Safari, Chrome and Edge. For a list of browser support see here.
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/URL/URL
https://url.spec.whatwg.org/
Eric Bidelman, an engineer at Google, recommends using this polyfill for unsupported browsers.
I found this ages ago, very easy:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
Then call it like this:
var fType = getUrlVars()["type"];
You can get the query string in location.search, then you can split everything after the question mark:
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
// Now you can get the parameters you want like so:
var abc = params.abc;
A super simple way using URLSearchParams.
function getParam(param){
return new URLSearchParams(window.location.search).get(param);
}
It's currently supported in Chrome, Firefox, Safari, Edge, and others.
I wrote a more simple and elegant solution.
var arr = document.URL.match(/room=([0-9]+)/)
var room = arr[1];
Here is a recursive solution that has no regex, and has minimal mutation (only the params object is mutated, which I believe is unavoidable in JS).
It's awesome because it:
Is recursive
Handles multiple parameters of the same name
Deals well with malformed parameter strings (missing values, so on)
Doesn't break if '=' is in the value
Performs URL decoding
And lastly, It's awesome because it...argh!!!
Code:
var get_params = function(search_string) {
var parse = function(params, pairs) {
var pair = pairs[0];
var parts = pair.split('=');
var key = decodeURIComponent(parts[0]);
var value = decodeURIComponent(parts.slice(1).join('='));
// Handle multiple parameters of the same name
if (typeof params[key] === "undefined") {
params[key] = value;
} else {
params[key] = [].concat(params[key], value);
}
return pairs.length == 1 ? params : parse(params, pairs.slice(1))
}
// Get rid of leading ?
return search_string.length == 0 ? {} : parse({}, search_string.substr(1).split('&'));
}
var params = get_params(location.search);
// Finally, to get the param you want
params['c'];
I made a function that does this:
var getUrlParams = function (url) {
var params = {};
(url + '?').split('?')[1].split('&').forEach(function (pair) {
pair = (pair + '=').split('=').map(decodeURIComponent);
if (pair[0].length) {
params[pair[0]] = pair[1];
}
});
return params;
};
Update 5/26/2017, here is an ES7 implementation (runs with babel preset stage 0, 1, 2, or 3):
const getUrlParams = url => `${url}?`.split('?')[1]
.split('&').reduce((params, pair) =>
((key, val) => key ? {...params, [key]: val} : params)
(...`${pair}=`.split('=').map(decodeURIComponent)), {});
Some tests:
console.log(getUrlParams('https://google.com/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('https://google.com/')); // Will log {}
console.log(getUrlParams('a=1&b=2&c')); // Will log {}
Update 3/26/2018, here is a Typescript implementation:
const getUrlParams = (search: string) => `${search}?`
.split('?')[1]
.split('&')
.reduce(
(params: object, pair: string) => {
const [key, value] = `${pair}=`
.split('=')
.map(decodeURIComponent)
return key.length > 0 ? { ...params, [key]: value } : params
},
{}
)
Update 2/13/2019, here is an updated TypeScript implementation that works with TypeScript 3.
interface IParams { [key: string]: string }
const paramReducer = (params: IParams, pair: string): IParams => {
const [key, value] = `${pair}=`.split('=').map(decodeURIComponent)
return key.length > 0 ? { ...params, [key]: value } : params
}
const getUrlParams = (search: string): IParams =>
`${search}?`.split('?')[1].split('&').reduce<IParams>(paramReducer, {})
See this
function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i<arrURLParams.length; i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0; i<arrURLParams.length; i++)
{
if (arrParamNames[i] == paramName)
{
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
The shortest way:
new URL(location.href).searchParams.get("my_key");
ECMAScript 6 solution:
var params = window.location.search
.substring(1)
.split("&")
.map(v => v.split("="))
.reduce((map, [key, value]) => map.set(key, decodeURIComponent(value)), new Map())
I use the parseUri library. It allows you to do exactly what you are asking for:
var uri = 'www.test.com/t.html&a=1&b=3&c=m2-m3-m4-m5';
var c = uri.queryKey['c'];
// c = 'm2-m3-m4-m5'
I use
function getVal(str) {
var v = window.location.search.match(new RegExp('(?:[\?\&]'+str+'=)([^&]+)'));
return v ? v[1] : null;
}
this question has too many answers, so i'm adding another one.
/**
* parses and returns URI query parameters
*
* #param {string} param parm
* #param {bool?} asArray if true, returns an array instead of a scalar
* #returns {Object|Array}
*/
function getURIParameter(param, asArray) {
return document.location.search.substring(1).split('&').reduce(function(p,c) {
var parts = c.split('=', 2).map(function(param) { return decodeURIComponent(param); });
if(parts.length == 0 || parts[0] != param) return (p instanceof Array) && !asArray ? null : p;
return asArray ? p.concat(parts.concat(true)[1]) : parts.concat(true)[1];
}, []);
}
usage:
getURIParameter("id") // returns the last id or null if not present
getURIParameter("id", true) // returns an array of all ids
this copes with empty parameters (those keys present without "=value"), exposure of both a scalar and array-based value retrieval API, as well as proper URI component decoding.
Here is my solution. As advised by Andy E while answering this question, it's not good for your script's performance if it's repeatedly building various regex strings, running loops etc just to get a single value. So, I've come up with a simpler script that returns all the GET parameters in a single object. You should call it just once, assign the result to a variable and then, at any point in the future, get any value you want from that variable using the appropriate key. Note that it also takes care of URI decoding (i.e things like %20) and replaces + with a space:
function getUrlQueryParams(url) {
var queryString = url.split("?")[1];
var keyValuePairs = queryString.split("&");
var keyValue = [];
var queryParams = {};
keyValuePairs.forEach(function(pair) {
keyValue = pair.split("=");
queryParams[keyValue[0]] = decodeURIComponent(keyValue[1]).replace(/\+/g, " ");
});
return queryParams;
}
So, here are are a few tests of the script for you to see:
// Query parameters with strings only, no special characters.
var currentParams = getUrlQueryParams("example.com/foo?number=zero");
alert(currentParams["number"]); // Gives "zero".
// For the URL you stated above...
var someParams = getUrlQueryParams("www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ");
alert(someParams["c"]); // Gives "m2-m3-m4-m5".
// For a query params with URI encoding...
var someParams = getUrlQueryParams("www.example.com/t.html?phrase=a%20long%20shot&location=Silicon+Valley%2C+USA");
alert(someParams["phrase"]); // Gives "a long shot".
alert(someParams["location"]); // Gives "Silicon Valley, USA".
The easiest way using the replace() method:
From the urlStr string:
paramVal = urlStr.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
or from the current URL:
paramVal = document.URL.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
Explanation:
document.URL - interface returns the document location (page url) as a string.
replace() - method returns a new string with some or all matches of a pattern replaced by a replacement.
/.*param_name=([^&]*).*/ - the regular expression pattern enclosed between slashes which means:
.* - zero or more of any characters,
param_name= - param name which is serched,
() - group in regular expression,
[^&]* - one or more of any characters excluding &,
| - alternation,
$1 - reference to first group in regular expression.
var urlStr = 'www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5';
var c = urlStr.replace(/.*c=([^&]*).*|(.*)/, '$1');
var notExisted = urlStr.replace(/.*not_existed=([^&]*).*|(.*)/, '$1');
console.log(`c === '${c}'`);
console.log(`notExisted === '${notExisted}'`);
Yet another suggestion.
There are some good answers already, but I found them needlessly complex and hard to understand. This is short, simple, and returns a simple associative array with key names corresponding to the token names in the URL.
I added a version with comments below for those who want to learn.
Note this relies on jQuery ($.each) for its loop, which I recommend instead of forEach. I find it simpler to ensure cross-browser compatibility using jQuery across the board rather than plugging in individual fixes to support whichever new functions aren't supported in older browsers.
Edit: After I wrote this I noticed Eric Elliott's answer, which is almost the same, though it uses forEach, while I'm generally against (for reasons stated above).
function getTokens(){
var tokens = [];
var query = location.search;
query = query.slice(1);
query = query.split('&');
$.each(query, function(i,value){
var token = value.split('=');
var key = decodeURIComponent(token[0]);
var data = decodeURIComponent(token[1]);
tokens[key] = data;
});
return tokens;
}
Commented version:
function getTokens(){
var tokens = []; // new array to hold result
var query = location.search; // everything from the '?' onward
query = query.slice(1); // remove the first character, which will be the '?'
query = query.split('&'); // split via each '&', leaving us an array of something=something strings
// iterate through each something=something string
$.each(query, function(i,value){
// split the something=something string via '=', creating an array containing the token name and data
var token = value.split('=');
// assign the first array element (the token name) to the 'key' variable
var key = decodeURIComponent(token[0]);
// assign the second array element (the token data) to the 'data' variable
var data = decodeURIComponent(token[1]);
tokens[key] = data; // add an associative key/data pair to our result array, with key names being the URI token names
});
return tokens; // return the array
}
For the examples below we'll assume this address:
http://www.example.com/page.htm?id=4&name=murray
You can assign the URL tokens to your own variable:
var tokens = getTokens();
Then refer to each URL token by name like this:
document.write( tokens['id'] );
This would print "4".
You can also simply refer to a a token name from the function directly:
document.write( getTokens()['name'] );
...which would print "murray".
Or if you don't want to reinvent the URI parsing wheel use URI.js
To get the value of a parameter named foo:
new URI((''+document.location)).search(true).foo
What that does is
Convert document.location to a string (it's an object)
Feed that string to URI.js's URI class construtor
Invoke the search() function to get the search (query) portion of the url
(passing true tells it to output an object)
Access the foo property on the resulting object to get the value
Here's a fiddle for this.... http://jsfiddle.net/m6tett01/12/
For Single Parameter Value like this index.html?msg=1 use following code,
$(window).load(function(){
queryString();
});
function queryString()
{
var queryString = window.location.search.substring(1);
var varArray = queryString.split("="); //eg. index.html?msg=1
var param1 = varArray[0];
var param2 = varArray[1];
}
For All Parameter Value use following Code,
$(window).load(function(){
queryString();
});
function queryString()
{
var queryString = window.location.search;
var varArray = queryString.split("&");
for (var i=0;i<varArray.length;i++) {
var param = varArray[i].split("=");
//parameter-value pair
}
}
Here I am posting one example. But it's in jQuery. Hope it will help others:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>
<!-- URL: www.example.com/correct/?message=done&year=1990-->
<script type="text/javascript">
$(function(){
$.url.attr('protocol') // --> Protocol: "http"
$.url.attr('path') // --> host: "www.example.com"
$.url.attr('query') // --> path: "/correct/"
$.url.attr('message') // --> query: "done"
$.url.attr('year') // --> query: "1990"
});
</script>
I had the need to read a URL GET variable and complete an action based on the url parameter. I searched high and low for a solution and came across this little piece of code. It basically reads the current page url, perform some regular expression on the URL then saves the url parameters in an associative array, which we can easily access.
So as an example if we had the following url with the javascript at the bottom in place.
http://TestServer/Pages/NewsArchive.aspx?year=2013&Month=July
All we’d need to do to get the parameters id and page are to call this:
The Code will be:
<script type="text/javascript">
var first = getUrlVars()["year"];
var second = getUrlVars()["Month"];
alert(first);
alert(second);
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.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;
}
// Usage for URL: http://my.site.com/location?locationId=53cc272c0364aefcb78756cd&shared=false
var id = getUrlVars()["locationId"];
Got from here: http://jquery-howto.blogspot.ru/2009/09/get-url-parameters-values-with-jquery.html
Simple way
function getParams(url){
var regex = /[?&]([^=#]+)=([^&#]*)/g,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
then call it like getParams(url)
Elegant, functional style solution
Let's create an object containing URL param names as keys, then we can easily extract the parameter by its name:
// URL: https://example.com/?test=true&orderId=9381
// Build an object containing key-value pairs
export const queryStringParams = window.location.search
.split('?')[1]
.split('&')
.map(keyValue => keyValue.split('='))
.reduce<QueryStringParams>((params, [key, value]) => {
params[key] = value;
return params;
}, {});
type QueryStringParams = {
[key: string]: string;
};
// Return URL parameter called "orderId"
return queryStringParams.orderId;
It's the N++ time I am looking for a clean way to do this.
Will save this here in case I get back cause I know I will... 🙄
const parseUrlQuery = (value) => {
var urlParams = new URL(value).searchParams
return Array.from(urlParams.keys()).reduce((acc, key) => {
acc[key] = urlParams.getAll(key)
return acc
}, {})
}
console.log(parseUrlQuery('http://url/path?param1=A&param1=B&param2=ABC&param3=61569'))
Here is what I do:
var uriParams = getSearchParameters();
alert(uriParams.c);
// background functions:
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
// http:localhost:8080/path?param_1=a&param_2=b
var getParamsMap = function () {
var params = window.location.search.split("&");
var paramsMap = {};
params.forEach(function (p) {
var v = p.split("=");
paramsMap[v[0]]=decodeURIComponent(v[1]);
});
return paramsMap;
};
// -----------------------
console.log(getParamsMap()["param_1"]); // should log "a"

Remove multiple elements from array

I'd like to remove multiple specific elements from my array before it displays. Here is the code I have but it results in none of the elements being displayed:
$('[data-fancybox]').on('click', function() {
var visibleLinks = $('.fancybox:visible');
$.fancybox.open( visibleLinks, {
//options go here
caption: function (instance, item) {
var caption, link, collectTags, tags, filterTags, filteredTags;
function format(tpl, binding) {
if (typeof binding != 'function') return format(tpl, function (_, name) {
return binding[name];
});
return tpl.replace(/\$(\w+)/g, binding);
}
caption = $(this).data('caption');
link = format('<br>See more pictures', item);
collectTags = $(this).parent().attr("class").split(' ');
function createTag(it) {
return format("<a href='$site$it'>$it</a>", {
site: (it == 'wedding' || it == 'concert') ? 'http://example.com/gallery/#filter=.' : 'http://example.com/gallery/#filter=.',
it: it
});
}
filterTags = ['churchevent', 'corporate'];
filteredTags = tags.filter(function(itm){return itm!== filterTags});
tags = $.map(collectTags, createTag);
return [].concat(caption ? [caption, link] : link).concat(filteredTags.slice(1).join(', ')).join('<br>');
}
}, visibleLinks.index( this ) );
return false;
});
I'm supposing that, since you wrote "remove multiple specific elements" you want to REMOVE filterTags.
If that's the case then change this:
filterTags = ['churchevent', 'corporate'];
filteredTags = tags.filter(function(itm){return itm!== filterTags});
tags = $.map(collectTags, createTag);
return [].concat(caption ? [caption, link] : link).concat(filteredTags.slice(1).join(', ')).join('<br>');
to this:
filterTags = ['churchevent', 'corporate'];
tags = $.map(collectTags, createTag);
filteredTags = tags.filter((item)=>{
for(tag in filterTags) if (item.indexOf(filterTags[tag]) != -1) return false;
return true;
});
return [].concat(caption ? [caption, link] : link).concat(filteredTags.slice(1).join(', ')).join('<br>');
else just use != -1 instead of == -1 in the filter method.
What is "tags" in the context of tags.filter? I'm assuming it is some array. In either case, your filter is checking that an item in tags is not equal to filterTags, an array. Of course a single item in an array won't be equal to an array, so this will always return true, thus not filtering anything.
I think you probably want something like:
filteredTags = tags.filter(function(itm){return filterTags.indexOf(itm) !== -1});
Are you speaking about this array?
filterTags = ['churchevent', 'corporate'];
filteredTags = tags.filter(function(itm){return itm!== filterTags});
// Of note, you are creating tags just below this code. Should you move it up?
// Or rename tags => collectionTags???
// Either way, the filter function you are using is not doing what you expect.
tags.filter(function(itm){
// itm will be whatever, I'm guessing a string of some sort like "churchevent"
// Now you are trying to compare a string like "churchevent" to the
// array filterTags.
// This is what is happening...
return itm !== ['churchevent', 'corporate'];
// What you want to do is this in ES5
return (filterTags.indexOf(itm) === -1);
// or this in ES6
return !filterTags.includes(itm);
// Note the bang in front.
// TRUE will put itm in the tags array, FALSE will not.
}
Also, please reference the filter function in MDN.
Filter Function (MDN)

Matching a string to an array

I need your your help,
For some strange reason, when my var str is set to "OTHER-REQUEST-ASFA" the matched key comes back as "ASF" as opposed to "ASFA"
How can I get the returned output key of "ASFA" when my str is "OTHER-REQUEST-ASFA"
function test() {
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
for (var key in filenames) {
if (str.indexOf(key) != -1) { alert(filenames[key]) }
}
}
You could switch from
str.indexOf(key)
to
key.indexOf(str)
function test() {
var str = "OTHER-REQUEST-ASFA",
filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
},
key;
for (key in filenames) {
if (key.indexOf(str) != -1) {
console.log(filenames[key]);
}
}
}
test();
To answer why it's not working as you want...
You've got:
str.indexOf(key)
This checks for the first instance of key in str.
So in your loop, key first equals OTHER-REQUEST-ASF which is part of OTHER-REQUEST-ASFA, so the condition is true.
However, to do what you want to do, if you know the pattern is always going to be OTHER-REQUEST-XYZ, the easiest way is to use split():
str.split('-')[2]
will always return the last section after the last -
cause "OTHER-REQUEST-ASFA".indexOf("OTHER-REQUEST-ASF") will not return -1, so it will show "ASF"
You can also use static method Object.keys() to abtain array of keys
var test = () =>{
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
Object.keys(filenames).forEach(x => {
if ( x.indexOf(str) !== -1)
console.log(filenames[str]);
});
}
test();

Categories