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. Is there a better more straightforward way?
asked Jan 17, 2021 at 14:19
user4584963
2,5537 gold badges36 silver badges65 bronze badges
-
I was thinking my approach is wrong, instead of doing it the wrong way and then flattening it, I was wondering if there is a better way to begin withuser4584963– user45849632021年01月17日 14:23:41 +00:00Commented Jan 17, 2021 at 14:23
-
Ohh, I've understood now and 've voted to reopen. However, with the way the question is put together, it's easier to get misled though. How about you put your code first and explain the situation a bit better?Tibebes. M– Tibebes. M2021年01月17日 14:28:02 +00:00Commented Jan 17, 2021 at 14:28
-
@Tibebes.M ok doneuser4584963– user45849632021年01月17日 14:33:19 +00:00Commented Jan 17, 2021 at 14:33
1 Answer 1
You can use flatMap() instead of map() for such case.
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)
answered Jan 17, 2021 at 14:56
Tibebes. M
7,6285 gold badges19 silver badges40 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js