How to map hash pattern to string value? - javascript

I want to map what is in the location hash to a string. The mapping has to be based on a pattern below (:Placeholder would be arbitrary numbers, maybe RegEx?). What is the best way to handle this in a function?
'news/:NewsID/dup' => 'newsDuplicate',
'news/:NewsID' => 'newsDetail',
'news/:NewsID/authors' => 'authorsList',
'news/:NewsID/authors/' => 'authorsList',
'news/:NewsID/authors/create' => 'authorsCreate',
'news/:NewsID/authors/:AuthorID' => 'authorDetail',
'news/:NewsID/authors/:AuthorID/orders' => 'orders',
'news/:NewsID/authors/:AuthorID/workflow' => 'workflow',
'news/:NewsID/authors/:AuthorID/tags' => 'tags'
I am trying to highlight the correct button in a navigation and wanted a function like handleNav() which would highlight the right button based on the pattern.
For example, when at http://mydomain.com#!news/123/authors/987, then I can do something like this:
function handleNav() {
var current = ?? //get mapped string above
$('button.' + current).addClass('active').siblings().removeClass('active');
}
How do I get the "current" variable above based on the mapping? Not sure if a bunch of if-else statements would be the best way and I do not know much regex. Thanks for any help or insight.

Perhaps normalize the string before reading the mapping? Something like this:
var map = {
'news/ID/dup' : 'newsDuplicate',
'news/ID' : 'newsDetail',
'news/ID/authors' : 'authorsList',
'news/ID/authors/' : 'authorsList',
'news/ID/authors/create' : 'authorsCreate',
'news/ID/authors/:AuthorID' : 'authorDetail',
'news/ID/authors/:AuthorID/orders' : 'orders',
'news/ID/authors/:AuthorID/workflow' : 'workflow',
'news/ID/authors/:AuthorID/tags' : 'tags'
}
function normalize(str) {
return str.replace(/news\/\d+/,'news/ID')
}
var current = map[normalize(url)];

Related

how to get to the key in an array of objects?

I hope you are all well 🙂
I would like to ask something that (I hope) is basic, i have this function that is responsible for returning the filtered objects with a specific "key" variable that translates to color or size.
Well I put the color and size variables inside an array of objects, I would like to know what is the terminology I have to use now in my "item[key]" to be able to get to my "color" variable as shown in the last picture 😦
picture showing what key im able to get now and then what key im looking to get!
Thanks in advance for any and all help, have a nice day!
here is the code for the two functions used in this process:
const [filtros,setFiltros] = useState({});
const gerirFiltros = (evento) =>{
const valor = evento.target.value;
console.log(evento.target.name + evento.target.value)
if (evento.target.name === "cor" ) {
const cor = evento.target.name
setFiltros( {
...filtros,
["variacoes"]:[{
[evento.target.name]:valor
}],
})
}
else {
setFiltros({
...filtros,
[evento.target.name]:valor,
}) // THIS IS JUST TO PASS TO PAGE #2 (https://pastebin.com/4GH3Mi3H) THE VARIABLE `filtros` THAT IS AN ARRAY WITH MANY FILTERS LIKE -> {marca:"Paz rodrigues"}, etc..
And the functio that receives the filter ( the one i think i need to change) :
useEffect(() => {
categoria &&
setProdutosFiltrados(
produtos.filter((item) =>
Object.entries(filtros).every(([key,value],i) =>
//console.log("key ->" + key + "value->" + value[0].cor) )
item[key].includes(value)
)
)
)
You can use some()
useEffect(() => {
categoria &&
setProdutosFiltrados(
produtos.filter((item) =>
Object.entries(filtros).every(([key,value],i) =>{
//Here the value is an array 'variacoes' so to check colors use filter to get all the elements of 'variacoes' array;
//Also assuming that the color you are passing will be available here as item[key]
var allColors = item.map(i=>i.cor)
return value.some((val)=>allColors.includes(val.cor))
}
)
)
)

How to get value of URL query parameter with dynamic name?

I need to extract the value of a query parameter in a URL, but the parameter changes on each page.
For example, I want to get the color variable, but it always changes based on the productID. In this case it is 'dwvar_2000440926_color' but for another product it will be 'dwvar_545240926_color'. _color stays consistent, so I'd like to key off that:
https://www.example.com/us/2000440926.html?dwvar_2000440926_color=02
Thanks!
Basic regular expression would work
const myURL = new URL("https://www.example.com/us/2000440926.html?dwvar_2000440926_color=02")
console.log(myURL.search.match(/_color=([^&]+)/)[1]);
// more specfic
console.log(myURL.search.match(/dwvar_\d+_color=([^&]+)/)[1]);
You should use regex. Based on the description of the URL behavior you described you could do something like this:
const url = new URL("https://www.example.com/us/2000440926.html?dwvar_2000440926_color=02");
// Now url.search contains your query parameters.
// We gonna apply the regex on it to capturing the color id
let matches = url.search.match(/dwvar_\d+_color=(\d+)/)
// `matches` now contains the captured groups
console.log(matches[1])
// log : 02
Assuming that 1) you want to do this on the client side 2) the color param always begins with dwvar as shown in your example and 3) that there is never more than one dwvar param, you can use the following javascript:
let searchParams = new URLSearchParams(document.location.search);
searchParams.forEach((param_value, param_name) => {
if (param_name.indexOf('dwvar') == 0) {
console.log(param_value)
}
})
window.location.search.slice(1).split('&').reduce((acc, it) => {
const [key, val] = it.split('=');
return {
...acc,
[key]: val,
};
}, {});

How to use If statement in map function?

I'm using the map function to assign and populate table names only if object['Size/ scale of support']. is equal to a data that I'm passing using props. I've seemed to have got the logic right but the map is not allowing me to use my if statement. Is there a way I can use an if statement on my map function?
updateData(result) {
const data = result.data;
console.log(data);
let new_data = []
data.map(
(object) => {
if (object['Size/ scale of support'].toLowerCase() === this.props.data.toLowerCase()) {
console.log("support",object['Size/ scale of support'])
new_data.push(
{
scale_of_support : object['Size/ scale of support'],
size_of_funding_instrument : object['Size of funding instrument'],
maturity_of_innovation_candidate : object['Maturity of innovation/ candidate'],
maturity_of_innovation_innovator : object['Maturity of innovation/ innovator'],
web_and_profile : object['Web and profile'],
source_of_information : object['Source of information'],
funding_instrument_name : object['Funding instrument name'],
}
)
}
}
)
this.setState({ cvs: new_data });
}
This code works:
var foo = [1,2,3];
foo.map(item => {
if (item === 2) console.log(item * 2);
return item;
});
which proves that your code is correct. If you use Typescript/Lint, then you may encounter errors because of this. If that's the case, you have several options to solve it:
Refactor
You can refactor your code, write a function that performs the conditional and its operation and only call that function from inside map.
Ternary operator
You may use the ternary operator as well, like:
mycondition ? myFunction() : myOtherValue;

Selecting specific field(child field?) from firebase in react Native

Here is my firebase:
"Locations" : {
"location01" : {
"image" :
"https://www.senecacollege.ca/content/dam/projects/seneca/homepage-assets/homepage_intl.jpg",
"instructorName" : " OSMAN H.",
"place" : "Seneca, Scarborough",
"timing" : "TBA"
},
"location02" : {
"image" : "https://media-exp1.licdn.com/dms/image/C561BAQHrVTRjljcYnw/company-background_10000/0?e=2159024400&v=beta&t=fp0LWqyEnnXvxjzzdfuCHhX2jflJyhAkS0lMLXsPFw0",
"instructorName" : "AIYAZ NOOR",
"place" : "UTSC, Scarborough",
"timing" : "4 PM - 6 PM"
}
},
I know that if I get the data like this, then I can select/filter the specific field I want.
let locationsRef = db.ref('/Locations');
locationsRef.once('value', snapshot => {
let data = snapshot.val()
let locationsList = Object.values(data)
console.log(locationsList);
})
This unfortunately will give all the data as an array and displays each object. If the /locations branch had many records, it would take up space and in my opinion not best practice. Is there any way to select the 'place' field ONLY. The keys 'location01' and 'location02' can be anything. So I can't do something like (location/location01), this would take me into specific branch then. I want to get the 'place' field from all the branches.
I researched alot and had no luck. Any ideas/help are much appreciated!
Thank you in advance
I think what you are looking for is the .map function in JavaScript.
You can map over your locations object like this:
const locationsRef = db.ref('/Locations');
locationsRef.once('value', snapshot => {
let data = snapshot.val()
let locationsList = Object.values(data)
locationsList.map((location, index) => {
console.log(location.place);
// here you can do whatever you want with every single location object
// for example return a View that displays only the place
return <View><Text>{location.place}</Text></View>
});
});
You can read more about the .map function in the MDN docs here.
P.S.
I changed your use of let to const in case your DB data is a constant that you are not changing in this particular View.

Conditional statement within template literal concatenation?

I am making an API call like this:
posts: (ppp, page) =>
requests.get(`/wp-json/wp/v2/posts?per_page=${ppp}&page=${page}`)
I am not always going to be passing in posts per page or page though, so I would like to only concatenate those variables if they exist. I tried below but I can't seem to get the formatting down:
requests.get(`/wp-json/wp/v2/posts?`${ppp ? `'per_page='${ppp} : `''` `${page} ? `'&page=' ${page}` :''`)
Besides that your second solution contains syntax errors, it also isn't the most readable way to do that...
But why are you trying to reinvent the wheel?
You can use the URL API which is available both on the client-side and in Node.js:
posts: (ppp, page) => {
const url = new URL('/wp-json/wp/v2/posts')
if(ppp) url.searchParams.append('per_page', ppp)
if(page) url.searchParams.append('page', page)
return requests.get(url.href)
}
However, if you can't use the above solution for some reason, you can still implement a similar algorithm that works like the above solution. For example, you can use an array:
posts: (ppp, page) => {
const urlParams = []
if(ppp) urlParams.push(`per_page=${ppp}`)
if(page) urlParams.push(`page=${page}`)
return requests.get(`/wp-json/wp/v2/posts?${ urlParams.join('&') }`)
}
Or an even more flexible solution:
posts: (ppp, page) => {
const urlParams = {
per_page: ppp, //per_page=ppp
page, //page=page
//Add more here if you want
}
return requests.get(`/wp-json/wp/v2/posts?${
Object
.entries(urlParams)
.filter(([k, v]) => v) //If value is truthy
.map(e => e.join('=')) //Concatenate key and value with =
.join('&') //Concatenate key-value pairs with &
}`)
}
But, if you want to stick to you version, here's a fixed example of it:
requests.get(`/wp-json/wp/v2/posts?${ppp ? `per_page=${ppp}` : ''}${(ppp && page) ? '&' : ''}${page ? `page=${page}` : ''}`)

Categories