The "double map" may not be sufficient enough. Though the idea is valid, your problem consists of "getting the properties of an object" twice, while also assigning its right values to it.
A solution using two maps could look like this:
const dates = Object.keys(data.rates);
const results = dates.map((date) => {
const currencies = Object.keys(data.rates[date]);
return currencies.map(currency => {
return {
date: date,
rate: data.rates[date][currency],
currency: currency,
};
});
})
Though this will be an array of arrays! This makes sense if you assume you have a rate with two currencies:
"2019-09-04": {
"USD": 0.1275393858,
"EUR": 1.47455,
},
This alone yields one array with two elements. An each other rate may generate a dynamic amount of objects in their own array.
You need to flatten that array of arrays. Alas, Array.prototype.flat and Array.prototype.flatMap is not widely supported.
So you may be better off using a library like lodash.
So with that being said you get your wanted result via:
_.flatten(results), null, 4)
Lodash also supports a flatMap, then a solution could be written like:
import * as _ from "lodash";
const data = {
"rates": {
"2019-09-04": {
"USD": 0.1275393858,
"EUR": 1.47455,
},
"2019-09-05": {
"USD": 0.1275638511,
},
},
};
const dates = Object.keys(data.rates);
const results = _.flatMap(dates, (date) => {
const currencies = Object.keys(data.rates[date]);
return currencies.map(currency => {
return {
date: date,
rate: data.rates[date][currency],
currency: currency,
};
});
});
console.log(JSON.stringify(results, null, 4));
Will print:
[
{
"date": "2019-09-04",
"rate": 0.1275393858,
"currency": "USD"
},
{
"date": "2019-09-04",
"rate": 1.47455,
"currency": "EUR"
},
{
"date": "2019-09-05",
"rate": 0.1275638511,
"currency": "USD"
}
]