繁体   English   中英

从数组创建嵌套的 Object

[英]Create nested Object from an Array

我有以下对象数组

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
},
]

我想创建一个看起来像这样的 Object

    {
            USD: 
            {
              buy:1.5781,
              sell:1.6484,
    
            },
            EUR:
            {
              buy:1.948,
              sell:1.963,
            },
            GBP: 
            {
              buy:2.1184,
              sell:2.1894,
            }
          }

目前我正在手动分配值,但我不认为这是可扩展的。 我正在寻找更有效的方法。

我会 go 为Object.fromEntries和 object Z65E8800B5C6800AAD8ZFCF88A88

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

你可以像这样使用Array.prototype.reduce()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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