Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!