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

163
Visualizações
How to creat an array that includes multiples elements from an object from the local Storage

I would like to creat an array that includes every products id's from the local storage object of my shopping website cart. The thing is the function that i made generate an array for each product's id instead of one array with all the product's id in it

 var cartStorage = JSON.parse(localStorage.getItem("cart"));
        cartStorage.forEach(function (cart, index) {
        let cartIds = [cart._id];
        console.log(cartIds); // logs one array for each id instead of just one array with every id's
       });

I've been trying for hours but nothing seems to work, i'm guessing i have to use a forEach() but i can't make that work?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are defining let cartIds inside the loop. It gets created and recreated in every loop. So, of course, it contains only one element. Define it outside the loop, and in the loop, push stuff in it.

const cartStorage = JSON.parse(localStorage.getItem("cart"));
let cartIds = [];
cartStorage.forEach(cart => cartIds.push(cart._id));
console.log(cartIds);

Or even better :

const cartStorage = JSON.parse(localStorage.getItem("cart"));
const cartIds = cartStorage.map(cart => cart._id);
console.log(cartIds);

Also, note that, if you have no "cart" in your localStorage, getItem will return null, and your code will crash. You need to handle this case.

about 4 years ago · Juan Pablo Isaza Relatório

0

Create the variable outside of the loop, and push the values into this array.

 var cartIds = []
 var cartStorage = JSON.parse(localStorage.getItem("cart"));
    cartStorage.forEach(function (cart, index) {
     cartIds.push(cart._id)
   });
 console.log(cartIds) // this has all the pushed values inside
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