将嵌套对象数组转换为对象数组的最佳方法
Posted
技术标签:
【中文标题】将嵌套对象数组转换为对象数组的最佳方法【英文标题】:Best way to turn array of nested objects into array of objects 【发布时间】:2021-04-21 23:52:14 【问题描述】: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()
,但这似乎是一种迂回的方式来获得我正在寻找的东西。有没有更好更直接的方法?
【问题讨论】:
我在想我的方法是错误的,而不是用错误的方式做,然后把它弄平,我想知道是否有更好的方法开始 哦,我现在明白了,已经投票决定重新开放。但是,通过将问题放在一起的方式,很容易被误导。你先把你的代码放在前面,然后再解释一下情况怎么样? @Tibebes.M ok 完成 【参考方案1】:对于这种情况,您可以使用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)
【讨论】:
以上是关于将嵌套对象数组转换为对象数组的最佳方法的主要内容,如果未能解决你的问题,请参考以下文章
Javascript:将数组转换为对象的最佳方法是啥? [复制]