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.
2 Answers 2
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);
answered Dec 8, 2020 at 17:11
trincot
357k38 gold badges282 silver badges339 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Dec 8, 2020 at 17:03
Guerric P
32k6 gold badges61 silver badges109 bronze badges
5 Comments
Bergi
What's that IIFE good for? Also
arr is not an array.Guerric P
It's to extract needed properties
Bergi
But why not just destrucure the
cur parameter to the reducer directly? (acc, {IsoCode, Buy, Sell}) => { acc[IsoCode] = {Buy, Sell}; return acc; }adiga
Something like this might be better:
sorted.reduce((acc, { IsoCode, ...rest }) => ({ ...acc, [IsoCode]: rest }),{})Guerric P
It just depends whether OP wants to extract these exact keys or the rest, which is not precised. Also, having a pure function instead of mutating the accumulator is just one's opinion.
Explore related questions
See similar questions with these tags.
lang-js
reduce().