简体   繁体   中英

Create nested Object from an Array

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.

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM