Search code examples
angulartypescriptangular7cartshopping-cart

How to get specific data from json object in array (Local Storage) - Angular 7


In my angular project have shopping cart feature. Every product i will store in local storage as a object in array.

1. So i want to get each product price (productPrice) from json object, to show total price in cart.

2. Anther thing is i want to delete specific object from local storage, array of cart item by project ID.

can any help me to do that.

Cart.component.ts

public cartItems :any; 

ngOnInit() {
  if(this.cartService.getFromLocalStrorage()){
    this.cartItems = this.cartService.getFromLocalStrorage(); 
    console.log(this.cartItems); //result show in below  
  }
}

Cart-services.service.ts

public getFromLocalStrorage() {
  const  cart =  JSON.parse(localStorage.getItem('cartObject'));
  return cart;
}

Result - Console Log

(4) [{…}, {…}, {…}, {…}]

0:
productId: 2
productName: "product 2"
productPrice: 1000
productQuantity: 9
productSelectedTypeId: 1
productSelectedTypeName: "100 ml"

////---------------------------

In local storage

 [{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,…}

Solution

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