Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

76
Vistas
JavaScript For Loop Not Returning Expected String

I'm trying to pull the names of purchased products into an advertising pixel for reporting purposes. An example is in the below image:

enter image description here

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!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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();
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda