簡體   English   中英

將嵌套對象數組轉換為對象數組的最佳方法

[英]Best way to turn array of nested objects into array of objects

 const data = [ { 'UTMEH5': { descr: { ordertype: 'limit', pair: 'XBT/USD', price: '5000.00000', }, status: 'open', vol: '0.00200000', }, }, { '3F2TYE': { descr: { ordertype: 'limit', pair: 'XBT/USD', price: '10000.00000' }, status: 'open', vol: '0.00200000', }, }, ] const orders = data.map((order) => { return Object.entries(order).map(([key, value]) => ({ orderid: key, pair: value['descr']['pair'], vol: value['vol'], price: value['descr']['price'], ordertype: value['descr']['ordertype'], status: value['status'], }))}) console.log(orders)

使用上面的代碼,我得到了這個:

[
  [
    {
      "orderid": "UTMEH5",
      "pair": "XBT/USD",
      "vol": "0.00200000",
      "price": "5000.00000",
      "ordertype": "limit",
      "status": "open"
    }
  ],
  [
    {
      "orderid": "3F2TYE",
      "pair": "XBT/USD",
      "vol": "0.00200000",
      "price": "10000.00000",
      "ordertype": "limit",
      "status": "open"
    }
  ]
]

但我想要這個:

[
    {
      "orderid": "UTMEH5",
      "pair": "XBT/USD",
      "vol": "0.00200000",
      "price": "5000.00000",
      "ordertype": "limit",
      "status": "open"
    },
    {
      "orderid": "3F2TYE",
      "pair": "XBT/USD",
      "vol": "0.00200000",
      "price": "10000.00000",
      "ordertype": "limit",
      "status": "open"
    }
]

有了重復的建議,我似乎可以使用.flat() ,但這似乎是一種迂回的方式來獲得我正在尋找的東西。 有沒有更好更直接的方法?

對於這種情況,您可以使用flatMap()而不是map()

 const data = [{ 'UTMEH5': { descr: { ordertype: 'limit', pair: 'XBT/USD', price: '5000.00000', }, status: 'open', vol: '0.00200000', }, }, { '3F2TYE': { descr: { ordertype: 'limit', pair: 'XBT/USD', price: '10000.00000' }, status: 'open', vol: '0.00200000', }, }, ] const orders = data.flatMap((order) => Object.entries(order).map(([key, value]) => ({ orderid: key, vol: value['vol'], status: value['status'], ...value['descr'], // you can use spread operator here for brevity as well }))) console.log(orders)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM