Skip to content Skip to sidebar Skip to footer

How To Get The Numbers From A String To Calculate Them Together In Angular/typescript?

I have a longer string: cartString with Strings in it Console OutPut after console.log(this.cartString);: [{'Name':'A','Price':2.99},{'Name':'B','Price':5.99},{'Name':'C','Price':8

Solution 1:

You can use Array#map to get the Price property and Array#reduce and parseFloat to calculate the sum:

const obj = [{"Name":"A","Price":"2.99"},{"Name":"B","Price":"5.99"},{"Name":"C","Price":"8.99"}]
const priceSum = obj.map(e => parseFloat(e.Price)).reduce((a, b) => a + b);
console.log(priceSum);

Solution 2:

You can use regex to check if there are numbers and could get the positions, so that you can extract the strings from those positions and just parseInt() it. Since the console output is an array with objects, its much easier.

Now you can use *ngFor to loop through each items and then you can display each one's name and price by item['Name'] and item['Price'], or item.Name and item.Price


Post a Comment for "How To Get The Numbers From A String To Calculate Them Together In Angular/typescript?"