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

166
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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