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?
CodePudding user response:
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.
CodePudding user response:
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