[英]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)
With the above code I am getting this:使用上面的代码,我得到了这个:
[
[
{
"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"
}
]
]
but I want this:但我想要这个:
[
{
"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"
}
]
With the duplicate suggestion it looks like I can use .flat()
, but that seems like a roundabout way to get what I'm looking for.有了重复的建议,我似乎可以使用
.flat()
,但这似乎是一种迂回的方式来获得我正在寻找的东西。 Is there a better more straightforward way?有没有更好更直接的方法?
You can use flatMap()
instead of map()
for such case.对于这种情况,您可以使用
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.