0

I have saving cart items in localStorage of javascript. I use product_id for index of array in javascript, this array contain of object with some property.

let cart = JSON.parse(localStorage.getItem('cart'));
cart[cartObject.product_id] = {
    quantity : cartObject.product_quantity,
    price : cartObject.product_price,
    holding : cartObject.product_holding
}
localStorage.setItem('cart' , JSON.stringify(cart));

the problem is for example when my product_id is 8, localStorage is :

0: null

1: null

2: null

4: null

5: null

6: null

7: null

8: {quantity: 15, price: 16000, holding: 44}

what about 4000 ? is localStorage goes overflow ?

this problem does not exist in php, I want to access directly to specific index of array. for example get cart[4432].price.

how to do that ?

thanks in advance

2
  • 1
    What did you try? Nothing prevents you to do card[4432] in JavaScript. Array can accept any index, but for performance reasons is advised to use objects if the indices are sparse Commented Sep 3, 2022 at 10:27
  • how to use object with key index like array ? Commented Sep 3, 2022 at 11:33

3 Answers 3

1

I think you need to change the way you store the products. Instead of using an Array, you can use an Object.

// Suppose localStorage.getItem('cart') contains an {} instead of []

let cart = JSON.parse(localStorage.getItem('cart')); // Should return {}

cart[cartObject.product_id] = {
    quantity : cartObject.product_quantity,
    price : cartObject.product_price,
    holding : cartObject.product_holding
}

localStorage.setItem('cart' , JSON.stringify(cart)); // Should save {"product_id": {"quantity": 1, "price": 100, "holding": "product_holder"}}

// If you want to loop like an Array, you would do the following:
Object.values(cart).forEach(function(product) {
  // Do something with your product...
})
Sign up to request clarification or add additional context in comments.

Comments

1

I guess the problem is that you use arrays for your task. A better way would be to use maps:

let cart = new Map( JSON.parse( localStorage.getItem('cart') ) );

cart.set( cartObject.product_id, {
  quantity : cartObject.product_quantity,
  price : cartObject.product_price,
  holding : cartObject.product_holding,
});

localStorage.setItem( 'cart', Array.from( cart ) );

2 Comments

Now can I access to cart[4432].quantity ?
@arefrazavi You can access it via cart.get( 4432 ).quantity (see developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… for reference)
0

Try to fix your code like this:

var colors=["red","blue"];
var index=1;

//insert "white" at index 1
colors.splice(index, 0, "white");   //colors =  ["red", "white", "blue"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.