EDIT I found the solution but this time I can not remove the comma from the end of the url. Below is my entire code. I just need to remove the from end of the url. i tried if statement but i failed.
var param = "";
//for loop for retrieving the selected values from array of object
for (let i = 0; i < that.productsSelected.length; i++) {
//console.log(that.productsSelected[i].id); + "<br>";
//console.log(that.productsSelected[i].quantity); + "<br>";
param += that.productsSelected[i].id +"&quantity="+ that.productsSelected[i].quantity;
if(!(i == that.productsSelected.length)){
param += ",";
}
}
console.log(param);
EDIT END
I am trying to add js variable in the url to add the products which user chose from a page.
that.productsSelected is array of javascript objects which I am getting from the page. Then to see the values I am using for loop, for now I am using console.log just for checking, see below.
//for loop for retrieving the selected values from array of object
for (let i = 0; i < that.productsSelected.length; i++) {
console.log(that.productsSelected[i].id); + "<br>";
console.log(that.productsSelected[i].quantity); + "<br>";
}
and I am getting values which is absolutely correct,
id 7464
quantity 1
Now my requirement is the value of id and quantity I want to add in the url for my online store.
window.location.href = "/cart/?add-to-cart=idvalue:"+quantity+",idvalue:"+quantity+",idvalue:"+quantity+",idvalue:"+quantity+",idvalue:"+quantity+"";
please note the product can be 2 or 8 or whatever it depends on user.
Can someone please help me? I am trying to get this solution for 1 week but miserably failed everytime
Use map() and join()
let cart_params = that.productsSelected.map(({id, quantity}) => `${id}:${quantity}').join(',');
window.location.href="/cart/?add-to-cart=" + cart_params;