How to pull conditional values from lists inside javascript objects - javascript

I have an object, with a list inside each key. What is the best way of returning the key, if the url string matches what's in the array.
For example in the code below, 'entertainment' would be returned as "/video" is in the entertainment array.
const url = "https://example.com/video";
const verticalList = {
autos:[],
entertainment:["/video", "/tech"],
foodanddrink:[],
healthandfitness:[],
homepage:["/home"],
lifestyle:["/ideas", "/executive-life"],
money:["/money-markets",],
news:["/briefing"],
sports:[],
travel:[],
weather:[]
}

You can use Object.entries to get a list of key-value pairs from your object and then run Array.filter to compare values against your url. In the last step you have to run Array.map to retrieve corresponding keys. String.includes can be used to check if one string is a substring of another.
const url = "https://example.com/video";
const verticalList = {
autos:[],
entertainment:["/video", "/tech"],
foodanddrink:[],
healthandfitness:[],
homepage:["/home"],
lifestyle:["/ideas", "/executive-life"],
money:["/money-markets",],
news:["/briefing"],
sports:[],
travel:[],
weather:[]
}
let matches = Object.entries(verticalList)
.filter(([key,value]) => value.some(x => url.includes(x)))
.map(([key,value]) => key);
console.log(matches)

Related

array different data inside a single array

how can I get all this array in one array without getting it one after the other like this in the code below? i mean saving the whole data inside one variable without giving a specific index of the array
here's the code
const favoriteProductone = data?.getAllLikeProduct[0]
const favoriteProductTwo = data?.getAllLikeProduct[1]
const favoriteProductThree = data?.getAllLikeProduct[2]
console.log(favoriteProductone?.Like[0])
console.log(favoriteProductTwo?.Like[0])
console.log(favoriteProductThree?.Like[0])
Just iterate the array like so:
if (!data) {
throw "data is falsy - there is nothing to process";
}
data.getAllLikeProduct.forEach(p => {
console.log(p.Like[0])
});

Selecting and adding values found with getElementsByClassName to dict or list

I am very new to JavaScript and I am trying to use it to select values from HTML using document.getElementsByClassName by putting index [0] from HTMLCollection. There is either one instance of the class being present or two or more.
const pizzatype = document.getElementsByClassName("pizzapizza")[0].innerHTML;
const pizzacheese = document.getElementsByClassName("cheesecheese")[0].innerHTML;
const pizzasauce = document.getElementsByClassName("saucesauce")[0].innerHTML;
const ordertotal = document.getElementsByClassName("fiyat")[0].innerHTML;
const order_dict = {
pizzatype,
pizzacheese,
pizzasauce,
ordertotal
}
const s = JSON.stringify(order_dict);
console.log(s); // returns {"pizzatype":"value1","pizzacheese":"value2","pizzasauce":"value3","ordertotal":"value4"}
The class is set like this:
<div class="cheesecheese card-text">${pizza.cheese}</div>
I tried experimenting with for loop, index(), .length, and others but I never got it to work. What would be the way to go to get return:
{
"pizzatype": "valuex1",
"pizzacheese": "valuex2",
"pizzasauce": "valuex3",
"ordertotal": "valuex4",
"pizzatype": "valuey1",
"pizzacheese": "valuey2",
"pizzasauce": "valuey3",
"ordertotal": "valuey4"
}
It should work even when there are more than 2 instances of those classes.
There is no way to store same key multiple times in Javascript object. You can use Entries syntax instead to get something similar.
Example of entries
[
[“pizzatype”, firstval],
[“pizzatype”, secondval],
]
Or you can use array of values inside your object.
To get result like so
{
pizzatype: [firstval,secondval],
…
}
You can get it with this way
{
pizzatype: Array.from(document.getElementsByClassName(“pizzapizza”)).map(elem => elem.innerHTML)
}

Assign values from one set of key/value pairs to keys of another?

I'm working with the outputs of an Intranet I don't control.
I have this string:
let template = 'LAWYER=|FIRM=|SUIT_DESCRIPTION=|DEF_COMMENT=|PLF_COMMENT=|';
It goes on longer, but that's the pattern.
Now there's another similar string, but with data assigned, as in this example:
let current= 'FIRM=Smith and Wesson LLP|SUIT_DESCRIPTION=It\'s a royal mess|PLF_COMMENT=some freeform text|LAWYER=Bob Smith';
Now, notice that not every element in template is necessarily represented in current, and the order may be different (if the latter fact is a big deal, I can ensure the order is the same).
What I'm trying to do, is take every element that is in current, and populate the matching element in template, if it exists. (or, alternatively and potentially preferred, insert every non-matching element in template into current, but ideally in the same order as template).
Using the date above, the result I'm looking for is:
result = 'LAWYER=Bob Smith|FIRM=Smith and Wesson LLP|SUIT_DESCRIPTION=It\'s a royal mess|DEF_COMMENT=|PLF_COMMENT=some freeform text|';
I'm not very accomplished with JavaScript :(
I tried various things in JSFiddle using split() and match() but I just made a mess of it.
// Convert the template to an array of keys
const getKeys = str => str.split('|').map(entry => entry.split('=')[0]);
// Convert the data to an object
const toObj = str => Object.fromEntries(str.split('|').map(entry => entry.split('=')));
// Reconcile the data with the template
const compile = (templateStr, dataStr) => {
const keys = getKeys(templateStr);
const data = toObj(dataStr);
return keys.reduce((results, key) => {
if(key) results.push([key, data[key] ?? '']);
return results;
}, []);
};
// Convert the results back into a string
const toString = data => data.map(entry => entry.join('=')).join('|') + '|';
// And then a test
let template = 'LAWYER=|FIRM=|SUIT_DESCRIPTION=|DEF_COMMENT=|PLF_COMMENT=|';
let current = 'FIRM=Smith and Wesson LLP|SUIT_DESCRIPTION=It\'s a royal mess|PLF_COMMENT=some freeform text|LAWYER=Bob Smith';
console.log(toString(compile(template, current)));

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,
};
}, {});

Dynamically populate string literally templates

Whenever I select a person from the list it grabs the id of a name and stores it an array with map.
I then have a string literal which gets populated with the ID.
const id = value.map(person => person.value)
console.log('from',id)
current output:
[u29219]
withe the results looking like this:
const results = await verifiedGet(`get_user/?$u29219?admin_form=True`, user.user)
and then if I add another person the array would look like this
[u29219, u302932]
results:
const results = await verifiedGet(`get_user/hello?$u29219,u302932?admin_form=True`, user.user)
When a user is added to the array I want to be able to iterate through the results with the ID only populating once if a user is selected twice
const results = await verifiedGet(`get_user/?$u29219?admin_form=True`, user.user)
const results = await verifiedGet(`get_user/?$u302932?admin_form=True`, user.user)
is this possible to do so?
I created a sandbox for a better understanding
https://codesandbox.io/s/modest-star-fegy7
I would take your unique id array and use Array.Join() to combine them with commas.
// Map the ids, and filter unique
const uniqueIds = value
.map((person) => person.value)
.filter((value, index, self) => self.indexOf(value) === index);
// Join the Ids and separate them with commas
const commaSeparatedIds = uniqueIds.join[','];
// Don't forget to make them safe for a URL
// You may be able to skip this if you are certain
// your string is safe
const uriSafeIds = encodeURIComponent(commaSeparatedIds);
// Finally, interpolate into your string literal template
// I wasn't sure if the extra $ in your code was intended
// so I left it in.
const url = `get_user/hello?$${uriSafeIds}?admin_form=True`;
const results = await verifiedGet(url, user.user);
In the line const id = user.map((person) => person);, we are looping through the 'user' array and for each iteration, we are just returning the element in that iteration. The 'map' function will return an Array of what will be returned in each iteration. So, basically, we are re-creating the user array in id.
const user = ["u29219", "u302932"];
// 'user' array is re-created here
const id = user.map((person) => person);
console.log("from", id);
const results = `get_user/?${id}admin_form=True`;
If your intention was to form the results string with each element in the array, this would be a way to do it using forEach:
user.forEach((person) => {
const results = `get_user/?${person}$admin_form=True`;
// remaining logic
});
Code-Sandbox
Can make the array unique, then concat or join to get the expected output.
const user = ["u29219", "u302932", "u302932"];
const uniqueItems = [...new Set(user)];
console.log("current uniqueItems", uniqueItems);
let results = "";
uniqueItems.forEach((person) => {
results = results.concat(`get_user/?${person}$admin_form=True `);
});
console.log("current output", results);

Categories