Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

77
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda