1

I'm getting a product list from a JSON file like

products.service

getProducts(): Observable<Product[]>{
    return this._http.get<Product[]>(this.configUrl); 
}

products.component

getProducts(): void{
    this.productsService.getProducts()
        .subscribe(productList =>{
         this.products = productList['products'];
        } );

}

product.interface

export interface Product {
    "quantity": number;
    "price": number;
    "available": boolean;
    "sublevel_id": number;
    "name": string;
    "id": string;
}

Json example

0:
 available: false
 id: "58b5a5b1b6b6c7aacc25b3fb"
 name: "aute"
 price: "$8,958"
 quantity: 308
 sublevel_id: 3
1:
 available: true
 id: "58b5a5b117bf36cf8aed54ab"
 name: "mollit"
 price: "$5,450"
 quantity: 891
 sublevel_id: 3

Price property is stored in json as string but I would like to store it in my variable this.products as a number because I will operate with them several times

How is the best way to do it?

Hector Landete
  • 357
  • 1
  • 6
  • 15
  • 2
    Why not storing price on JSON as a number? – GCSDC Dec 03 '18 at 21:21
  • Anyway, this seems a duplicate of: https://stackoverflow.com/questions/559112/how-to-convert-a-currency-string-to-a-double-with-jquery-or-javascript – GCSDC Dec 03 '18 at 21:25
  • @GCSDC I cannot change the format of the json file and is not the same because I know how to parse from string currency to float number (`parseFloat(p.price.replace(/[^0-9-.]/g, ''))`) but I want to store it directly as a number so I don't need to use that function each time I want to operate with it – Hector Landete Dec 03 '18 at 21:30

2 Answers2

1

Per your last comment, here's what you could do to store the values as desired in one go:

Replace:

this.products = productList['products'];

with:

this.products = productList['products']
  .map(product => ({ ...product, price: Number(product.price.replace(/[^0-9.-]+/g,'')) }));

I used the solution given in this answer to convert the currency value to a floating point number, as also mentioned in the comments.

Jeto
  • 14,596
  • 2
  • 32
  • 46
0

Store price in number format, instead of string.

0:
 available: false
 id: "58b5a5b1b6b6c7aacc25b3fb"
 name: "aute"
 price: 8958
 quantity: 308
 sublevel_id: 3
1:
 available: true
 id: "58b5a5b117bf36cf8aed54ab"
 name: "mollit"
 price: 5450
 quantity: 891
 sublevel_id: 3