How to get products name insade all arrray? - javascript

enter image description hereı want to set custom event with gtm but ı dont know how to get multple producs name . ı can get one of the items name but ı can not get all of them.
document.getElementsByClassName('cartAndCheckout__items')[0].innerText.split('\nStokta var\n3.329,00 TL')[0]
thats the code ı wrote

Seems you just need to iterate the elements that you find via document.getElementsByClassName
let products = []
let elements = document.getElementsByClassName('cartAndCheckout__items')
for(let i=0; i<elements.length; i++){
//products.push(elements[i].innerText)
//based on your comment,if you just want to get the name
let link = elements[i].querySelector('div.mb-2 a')
let title = link.getAttribute("title")
products.push(title)
}

document.getElementsByClassName('cartAndCheckout__items') returns a collection; it looks and mostly works like an array, even though it isn't an Array. You're getting the first item with [0], but you can also for instance loop over all the items:
let products = []
for (const element of document.getElementsByClassName('cartAndCheckout__items')) {
products.push(element.innerText.split('\nStokta var\n3.329,00 TL')[0])
}
Usually if you're building one list from another it's better to use map, but as the collection isn't actually an Array, you have to call it in a roundabout way:
const elements = document.getElementsByClassName('cartAndCheckout__items')
const products = Array.prototype.map.call(elements,
e => e.innerText.split('\nStokta var\n3.329,00 TL')[0])

Please note that ES6 is not supported in GTM, thus you either need to translate the above solution (which is basicly replace "const" and "let" with var :D) or implement the JavaScript natively and push the result to the DataLayer.

Related

insertBefore function for arrays and/or HTMLCollections?

Does there exist a function in vanilla JavaScript or jQuery that operates similarly to Node.insertBefore(), but for arrays and/or HTMLCollections?
An example could look something like:
var list = document.getElementsByClassName("stuff");
var nodeToMove = list[0];
var otherNode = list[4];
list.insertBefore(nodeToMove, otherNode);
Basically I'm trying to perform insertBefore() without manipulating the actual DOM, as I want the changes to only be applied to the DOM under certain conditions. If those conditions are met, then I would perform insertBefore() on the actual nodes.
To clarify, I'm looking for a function that would insert an element before a target element at a given index in an array, not necessarily at a given index. Examples I've seen using splice() usually insert an element at a given index, which sometimes puts the element before the target element, and sometimes after, depending on where the element to be moved originally was in the array. I'm looking for something that would reliably put the element to be moved before the target element.
HTMLCollection does not have an insertBefore method. jQuery can apply any jQuery methods both to a single element being selected, as well as many.
https://api.jquery.com/insertBefore/
There is no single method to do this in one step, but there doesn't need to be. If you convert the collection to an Array, you can call the Array.prototype.splice() method to achieve the same result.
Here's an example:
let ary = [1,2,3,4,5];
// Swap 2 and 3
// Start at the 3rd item and remove one item (3).
// Store the removed item
let removed = ary.splice(2,1);
// Start at the second item, don't remove anything, insert the removed
// item at that position
ary.splice(1,null,removed[0]);
// Log the result
console.log(ary);
And, with that knowledge, you can create your own more easily callable function:
let ary = [1,2,3,4,5];
function insertBefore(ary, newItem, target){
ary.splice(target,null,newItem);
}
// Insert 999 before the 3rd array item
insertBefore(ary,999,2)
console.log(ary);
You need to get the index you want, then use Array.splice.
Myself I would do something like this :
const myArr = ['Aurore', 'Dimitri', 'Alban', 'Frédéric'];
const insertBeforeThis = 'Alban';
const eltToInsert = 'Laura';
const index = myArr.findIndex(name => name === insertBeforeThis);
myArr.splice(index, 0, eltToInsert);
Please feel free to try it out in your browser's console. Note i used const for my array, as it fixes the type of the variable as an array but allow me to manipulate it.
MDN: Array.prototype.findIndex()
stackoverflow: How to insert an item into an array at a specific index (JavaScript)?
Have a happy coding time!

How can I get a list of User with their ID (list)?

I am trying to find out how to get a user list via their id in tabular form (array).
I've tried this :
let result = message.guild.members.get(id_list)
But it doesn't work ...
id list :
var id_list = [ '223515154229231616',
'447425491041910807',
'479932358422691840',
'464536970417143828',
'299429099611357185',
'332868897646837762',
'198346639843262464',
'266078466972057600',
'334270225895653379',
'198884536363253761',
'216595784286601216',
'358993909269135371',
'248894149162565647',
'396681438688182284',
'349270173011804171',
'358319021726236672',
'216136890963853313',
'282994966014459915',
'298171616968572930',
'257809919036751872',
'239365876846034944',
'502162147942596609',
'449391921840914444',
'473229490584158208' ]
The following should do the trick
let result = id_list.map(id => client.users.get(id));
Basically, you loop through all the ids you have using .map() and fetch the user associated.
You may want to remove all the undefined results (when your bot "does not know" the user linked to a specific id), in that case you need to add the following after the previous piece of code :
result = result.filter(r => r !== undefined);
Check both the documentation of .map() and .filter() for more information
This will not work as it is for one ID at a time, not an array of them. You would need to iterate over the IDs in the array, I suggest using a for loop for this, using id_list.length as one of the parameters. For example:
for(var i = 0; i <= id_list.length; i++) {
//make the request to get the member information
}
Also, just to make sure, you might be better off using client.users.get('id'); because if the user sends a direct message, there is no guild property so an error will be thrown.
You can use
let result = id_list.map(id => client.users.get(id).tag)
That should give back an array with like
['User#0000',
'NextUser#4821'
]

Is there a way to combine map and shift in Javascript?

I'm working with a buffer array that I am periodically checking. When I am mapping through the elements, I would like access the element using the shift method, this way I would get the next element in the array and would also remove it. Is there a way to do this in a map? Thank you!
I currently have a naive solution, which is prone to race conditions.
if (timestep) {
bufferArray.map((mvt) =>{
console.log(mvt)
});
bufferArray = [];
}
As I would like to go through the elements of the array one by one and remove the current element from the array. For this reason a simple and great solution is to use a while loop with the shift method. For example:
let arr = [0,1,2,3,4,5];
while (arr.length)
{
let current = arr.shift()
// do something with current
}

Possible to .push() to a dynamically named key?

I have an object that I would like to push an indeterminate amount of other objects to, using a loop. To keep it organized, I'd like to dynamically name the keys based on them amount of times the loop runs. I have the following:
let formsJson = {};
let counter = 1;
//savedForms are where the objects that I want to push reside
savedForms.forEach( form => {
formsJson['form'+counter] = JSON.parse(form.firstDataBit_json);
//This is where I'm having trouble
counter = counter + 1;
});
I can push the first bit of data fine, and name the key dynamically as well. But I need to push 2 more objects to this same dynamic key, and that's where I'm having trouble. If I try the obvious and do:
formsJson['form'+counter].push(JSON.parse(form.secondDataBit_JSON));
I don't get any output. Is there a way to accomplish this?
forEach() gives you access to the index already. No need to create the counter variable. Example usage. I would definitely recommend using a simple index, and not using the 'form'+counter key.
In your example, it's not clear to me that the value being assigned in the forEach loop is an array. So it's unclear if you can push to any given element in that. But generally that syntax should
Personally, I would prefer to have a function that outputs the entire value of the element. That would provide better encapsulation, testability, and help enforce default values. Something like:
function createItem(param1) {
let item = [];
item.push(param1.someElement);
if (foo) {
item.push(...);
} else {
item.push(...);
}
return item;
}
formsJson['form'+counter] = createItem( JSON.parse(form) )
So you're making formsJson['form'+counter] a by assigning the JSON parse, not an array as you want. Try this:
formsJson['form'+counter] = [];
formsJson['form'+counter].push(JSON.parse(form.firstDataBit_json));
formsJson['form'+counter].push(JSON.parse(form.secondDataBit_JSON));
Maybe you want to figure out something like this
savedforms.forEach((form, index) =>
formsJson[`form${index + 1}`] = [ JSON.parse(form.secondDataBit_JSON)])
Now you can push on the item
formsJson[`form${index + 1}`].push(JSON.parse(form.secondDataBit_JSON));`
Also here you'll save operation on incrementing it will be automaticly

Javascript object/array manipulation

Struggling with some javascript array manipulation/updating. Hope someone could help.
I have an array:
array('saved_designs'=array());
Javascript JSON version:
{"saved_design":{}}
I will be adding a label, and associated array data:
array("saved_designs"=array('label'=array('class'='somecssclass',styles=array(ill add more assoc elements here),'hover'=array(ill add more assoc elements here))))
Javascript version:
{"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}
I want to be able to append/modify this array. If 'label' already defined...then cycle through the sub data for that element...and update. If 'label' doesnt exist..then append a new data set to the 'saved_designs' array element.
So, if label is not defined, add the following to the 'saved_designs' element:
array('label2' = array('class'=>'someclass2',styles=array(),'hover=>array()')
Things arent quite working out as i expect. Im unsure of the javascript notation of [], and {} and the differences.
Probably going to need to discuss this as answers are provided....but heres some code i have at the moment to achive this:
//saveLabel = label the user chose for this "design"
if(isUnique == 0){//update
//ask user if want to overwrite design styles for the specified html element
if (confirm("Their is already a design with that label ("+saveLabel+"). Overwrite this designs data for the given element/styles?")) {
currentDesigns["saved_designs"][saveLabel]["class"] = saveClass;
//edit other subdata here...
}
}else{//create new
var newDesign = [];
newDesign[saveLabel] = [];
newDesign[saveLabel]["class"] = saveClass;
newDesign[saveLabel]["style"] = [];
newDesign[saveLabel]["hover"] = [];
currentDesigns["saved_designs"].push(newDesign);//gives error..push is not defined
}
jQuery("#'.$elementId.'").val(JSON.stringify(currentDesigns));
thanks in advance. Hope this is clear. Ill update accordingly based on questions and comments.
Shaun
It can be a bit confusing. JavaScript objects look a lot like a map or a dictionary from other languages. You can iterate over them and access their properties with object['property_name'].
Thus the difference between a property and a string index doesn't really exist. That looks like php you are creating. It's called an array there, but the fact that you are identifying values by a string means it is going to be serialized into an object in javascript.
var thing = {"saved_designs":{"label":{"class":"someclass","style":[],"hover":[]}}}
thing.saved_designs.label is the same thing as thing["saved_designs"]["label"].
In javascript an array is a list that can only be accessed by integer indices. Arrays don't have explicit keys and can be defined:
var stuff = ['label', 24, anObject]
So you see the error you are getting about 'push not defined' is because you aren't working on an array as far as javascript is concerned.
currentDesigns["saved_designs"] == currentDesigns.saved_designs
When you have an object, and you want a new key/value pair (i.e. property) you don't need a special function to add. Just define the key and the value:
**currentDesigns.saved_designs['key'] = newDesign;**
If you have a different label for every design (which is what it looks like) key is that label (a string).
Also when you were defining the new design this is what javascript interprets:
var newDesign = [];
newDesign is an array. It has n number of elements accessed by integers indices.
newDesign[saveLabel] = [];
Since newDesign is a an array saveLabel should be an numerical index. The value for that index is another array.
newDesign[saveLabel]["class"] = saveClass;
newDesign[saveLabel]["style"] = [];
newDesign[saveLabel]["hover"] = [];
Here explicitly you show that you are trying to use an array as objects. Arrays do not support ['string_key']
This might very well 'work' but only because in javascript arrays are objects and there is no rule that says you can't add properties to objects at will. However all these [] are not helping you at all.
var newDesign = {label: "the label", class: saveClass};
is probably what you are looking for.

Categories

Resources