How Can Someone Loop A JSON And Manipulate Its Values (convert To String, Set Fixed Decimals And Add Thousands Separator)?

06 November 2019 - 1 answer

I fetch data from a third party API which returns 170 key:value items that represent currency exchange rates. Now I would like to loop that Object and manipulate the value items.

My idea is to

1. change the decimal number to 5
1. replace the existing "." with a "comma"
1. add thousand separators (".") to any value where the figure before the decimals is
>= 1.000

Final output should look like e.g.

"BIF": 2088.228311 -->2.088,22831.

The formula for the separator is from this thread which works pretty fine in a different project of mine: How to print a number with commas as thousands separators in JavaScript

Somehow my attempt shown below directly ends up in a SO error.

``````let rates = {
"AED": 4.07055,
"AFN": 87.352472,
"ALL": 123.333245,
"AMD": 531.538368,
"ANG": 1.931339,
"AOA": 538.65376,
"ARS": 66.131175,
"AUD": 1.605893,
"AWG": 1.994881,
"AZN": 1.885024,
"BAM": 1.95844,
"BBD": 2.247575,
"BDT": 94.335008,
"BGN": 1.956646,
"BHD": 0.417802,
"BIF": 2088.228311,
"BMD": 1.108267,
"BND": 1.510167,
"BOB": 7.697558,
"BRL": 4.425866,
"BSD": 1.113173,
"BTC": 0.000118,
"BTN": 78.682856,
"BWP": 12.073536,
"BYN": 2.272208,
"BYR": 21722.032491,
}

Object.values(rates).forEach((value) => {
.toFixed(5);
.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
console.log(rates);
});``````

Pleas note you cannot change the original rates-object in a forEach-loop (take a look here). Also better use standartized tools to format numbers instead of implementing your own workarounds (take a look here)

``````let rates = {
"AED": 4.07055,
"AFN": 87.352472,
"ALL": 123.333245,
"AMD": 531.538368,
"ANG": 1.931339,
"AOA": 538.65376,
"ARS": 66.131175,
"AUD": 1.605893,
"AWG": 1.994881,
"AZN": 1.885024,
"BAM": 1.95844,
"BBD": 2.247575,
"BDT": 94.335008,
"BGN": 1.956646,
"BHD": 0.417802,
"BIF": 2088.228311,
"BMD": 1.108267,
"BND": 1.510167,
"BOB": 7.697558,
"BRL": 4.425866,
"BSD": 1.113173,
"BTC": 0.000118,
"BTN": 78.682856,
"BWP": 12.073536,
"BYN": 2.272208,
"BYR": 21722.032491
}

for(key in rates) {
rates[key] = new Intl.NumberFormat('de-DE', {
minimumFractionDigits: 5,
maximumFractionDigits: 5
}).format(rates[key]);

}
console.log(rates);``````