I'm trying to pull the names of purchased products into an advertising pixel for reporting purposes. An example is in the below image:
I'm trying to use the below function to loop through the object and return only the names, comma separated, as a string within a single variable. i'm using the below script:
function products() {
var items = _rsq.executor.sentWave.order_properties.order_items;
var product = "";
for (var i=0; i < items.length; i++) {
product += product + _rsq.executor.sentWave.order_properties.order_items[i].name + ",";
i++;
}
console.log(product);
}
products();
but it's only logging the first product like so: Purity Organic CBD Sleep Tea - Chamomille 15mg 18 Count,
Any help on what I'm missing would be greatly appreciated. Thanks!
If you just want your code to work, simply remove the extra i++ and change the += line slightly, like this:
function products() {
var items = _rsq.executor.sentWave.order_properties.order_items;
var product = '';
for (var i = 0; i < items.length; i++) {
product +=
_rsq.executor.sentWave.order_properties.order_items[i].name + ',';
}
console.log(product);
}
products();
However, I would suggest using one of these three alternatives to for loops. If you use methods like these, you will altogether avoid the issue of accidentally writing i++ twice, and your code will be more readable in general.
const items = [
{
id: 0,
name: 'Sleep',
price: 24.99,
},
{
id: 1,
name: 'Revive',
price: 24.99,
},
];
const productsUsingReduce = () => {
return items.slice(1).reduce((result, item) => {
return `${result}, ${item.name}`;
}, items[0].name);
};
const productsUsingFor = () => {
let result = items[0].name;
items.slice(1).forEach((item) => {
result += `, ${item.name}`;
});
return result;
};
const productsUsingJoin = () => {
return items
.map((item) => {
return item.name;
})
.join(', ');
};
console.log(productsUsingReduce());
console.log(productsUsingFor());
console.log(productsUsingJoin());
The only* reason I have found where you actually need a for loop is if you are using await to run multiple asynchronous calls in a specific order.
*If you are forced to use old version(s) of javascript/node for some strange reason, then you may end up having to use for loops.
When you do x += 2, it is the same as if you did x = x + 2, so the second product in product += product has to be removed in order to get the correct result.
You can shorten the _rsq.executor.sentWave.order_properties.order_items to just items, because you declared it before the for-loop as items and you never changed it.
Also, you added extra i++, which is not necessary, because you already increment i in the for-loop, specifically at the end of this line: for (var i=0; i < items.length; i++).
This should work:
function products() {
var items = _rsq.executor.sentWave.order_properties.order_items;
var product = "";
for (var i=0; i < items.length; i++) {
product += items[i].name + ",";
}
console.log(product);
}
products();