Reputation: 51
I have the following array of objects
const sorted = [
{
IsoCode: "EUR",
Buy: 1.948,
Sell: 1.963
},
{
IsoCode: "GBP",
Buy: 2.1184,
Sell: 2.1894
},
{
IsoCode: "USD",
Buy: 1.5781,
Sell: 1.6484
},
]
and I want to create an Object looking like this
{
USD:
{
buy:1.5781,
sell:1.6484,
},
EUR:
{
buy:1.948,
sell:1.963,
},
GBP:
{
buy:2.1184,
sell:2.1894,
}
}
Currently I'am assigning the values manually, but I don't think this is scalable. I'm looking for more effective approach.
Upvotes: 0
Views: 57
Reputation: 350137
I would go for Object.fromEntries
and the object rest syntax:
const sorted = [{IsoCode: "EUR",Buy: 1.948,Sell: 1.963},{IsoCode: "GBP",Buy: 2.1184,Sell: 2.1894},{IsoCode: "USD",Buy: 1.5781,Sell: 1.6484},];
let res = Object.fromEntries(sorted.map(({IsoCode, ...rest}) => [IsoCode, rest]));
console.log(res);
Upvotes: 3
Reputation: 31805
You could use Array.prototype.reduce()
like this:
const sorted = [{
IsoCode: "EUR",
Buy: 1.948,
Sell: 1.963
}, {
IsoCode: "GBP",
Buy: 2.1184,
Sell: 2.1894
}, {
IsoCode: "USD",
Buy: 1.5781,
Sell: 1.6484
},
]
const obj = sorted.reduce(
(acc, { IsoCode, Buy, Sell }) =>
(acc[IsoCode] = { Buy, Sell }) && acc,
{}
);
console.log(obj);
Upvotes: 2