I have a data set that I query from a database that gives the following object.
[{
item_id: 'adsfsdf',
order_no: '2499321',
line_no: 8,
uom: 'EA',
qty: 0,
req_date: 2021-06-07T00:00:00.000Z,
tracking: 'asdfsad',
carrier_name: 'UPS Ground',
carrier_address: 'asdf'
},
{
item_id: 'asdfasdf',
order_no: '2499321',
line_no: 9,
uom: 'EA',
qty: 2,
req_date: 2021-06-07T00:00:00.000Z,
tracking: 'asdf',
carrier_name: 'UPS Ground',
carrier_address: 'asdfasdf'
},
{
item_id: 'asdfsdf',
order_no: '2499903',
line_no: 1,
uom: 'EA',
qty: 4,
req_date: 2021-06-04T00:00:00.000Z,
tracking: null,
carrier_name: 'UPS Ground',
carrier_address: 'asdfasdfa'
}]
I would like to reduce the array into a smaller array grouped by the order_no value.
So far, I have something like this:
request.query(q).then(function (res) {
let newObj = []
res.recordset.forEach((e) => {
newObj.push({[e.order_no] : [e]})
})
let finalObj = newObj.reduce((a, obj) => {
let [k, v] = Object.entries(obj)[0]
a[k] = a[k] + v
return a
}, {})
let final = Object.entries(finalObj).map(([k,v]) => {
return {[k]:v}
})
dbConn.close();
}).catch(function (err) {
console.log(err);
dbConn.close();
});
When I console.log the "final" variable, this is how it looks:
{
'2499321': 'undefined[object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object][object Object]'
},
{ '2499903': 'undefined[object Object]' },
{ '2501438': 'undefined[object Object][object Object]' },
{ '2501803': 'undefined[object Object][object Object]' },
{ '2502223': 'undefined[object Object]' },
{ '2502627': 'undefined[object Object]' },
{ '2503022': 'undefined[object Object][object Object]' },
{ '2503169': 'undefined[object Object]' }
]
Expected result would be something like:
['2499321': [{
item_id: 'adsfsdf',
line_no: 8,
uom: 'EA',
qty: 0,
req_date: 2021-06-07T00:00:00.000Z,
tracking: 'asdfsad',
carrier_name: 'UPS Ground',
carrier_address: 'asdf'
},{
item_id: 'asdfasdf',
line_no: 9,
uom: 'EA',
qty: 2,
req_date: 2021-06-07T00:00:00.000Z,
tracking: 'asdf',
carrier_name: 'UPS Ground',
carrier_address: 'asdfasdf'
}]
//Then next order_no with objects as nested array
I am not sure why it shows the "undefined" and how do I expand the object? Is this the correct way of achieving this result?
All help is appreciated.
Thank you.