In my angular project have shopping cart feature. Every product i will store in local storage as a object in array.
can any help me to do that.
public cartItems :any;
ngOnInit() {
if(this.cartService.getFromLocalStrorage()){
this.cartItems = this.cartService.getFromLocalStrorage();
console.log(this.cartItems); //result show in below
}
}
public getFromLocalStrorage() {
const cart = JSON.parse(localStorage.getItem('cartObject'));
return cart;
}
(4) [{…}, {…}, {…}, {…}]
0:
productId: 2
productName: "product 2"
productPrice: 1000
productQuantity: 9
productSelectedTypeId: 1
productSelectedTypeName: "100 ml"
////---------------------------
[{productId: 2, productSelectedTypeId: 1, productSelectedTypeName: "100 ml", productQuantity: 9,…},…]
0: {productId: 2, productSelectedTypeId: 1, productSelectedTypeName: "100 ml", productQuantity: 9,…}
1: {productId: 2, productSelectedTypeId: 3, productSelectedTypeName: "300 ml", productQuantity: 1,…}
2: {productId: 2, productSelectedTypeId: 2, productSelectedTypeName: "200 ml", productQuantity: 1,…}
3: {productId: 3, productSelectedTypeId: null, productSelectedTypeName: null, productQuantity: 24,…}
You can use a simple .map()
to extract an array only containing the prices, and a reduce()
to add up the total. Example below.
Solution
public ngOnInit(): void
{
if(this.cartService.getFromLocalStrorage())
{
this.cartItems = this.cartService.getFromLocalStrorage();
console.log(this.cartItems); //result show in below
const prices = this.cartItems.map(data => data.productPrice);
console.log(prices); // array of all the prices
const total = prices.reduce((a, b) => a + b));
console.log(total); // total prices from array of prices
}
}
To update the value in the local store you can filter the array and re-save it.
this.cartItems = this.cartItems.filter(data => data.productId !== 3);
localStorage.setItem('cartObject', JSON.stringify(this.cartItems));
Documentation
.map() // .reduce() // setting item by key in local storage // .filter()
Edit
For the multiplication including quantity of each product add it into the map
const prices = this.cartItems.map( data => (data.productPrice * data.productQuantity) );
console.log(prices); // array of all the prices
Then once again use the reduce()
function on this for the total prices of all including quantity.