Hey there! I'm new to JavaScript and currently using the Knex ORM for database interactions. I'm facing an issue where I am getting flat JSON as a result from my queries, but I need it in a different format as mentioned in the expected results section. I've tried some code snippets, but none of them are giving me the desired output. I've included my prototype code below along with the resulting output, which is not what I want. How can I achieve the actual result using lodash or ES6 higher order functions?
var data= [
{order_id: 1,kot_id: 10,price: 20,quantity: 2},
{order_id: 1,kot_id: 10,price: 100,quantity: 1},
{order_id: 1,kot_id: 10,price: 150,quantity: 1},
{order_id: 1,kot_id: 11,price: 55,quantity: 1},
{order_id: 1,kot_id: 11,price: 250,quantity: 3},
]
let objects = {}
let arr = []
result = data.forEach((item,index) => {
if(!objects.order_id) {
objects = {order_id: item.order_id,list: []}
arr.push(objects)
}
if(!objects.kot_id) {
objects.list.push({kot_id: item.kot_id,kot_list: []})
}
objects.list[index].kot_list.push({price: item.price,quantity: item.quantity})
})
console.log(JSON.stringify(arr,null,2))
RESULT OF THE ABOVE CODE
[
{
"order_id": 1,
"list": [
{
"kot_id": 10,
"kot_list": [
{
"price": 20,
"quantity": 2
}
]
},
{
"kot_id": 10,
"kot_list": [
{
"price": 100,
"quantity": 1
}
]
},
{
"kot_id": 10,
"kot_list": [
{
"price": 150,
"quantity": 1
}
]
},
{
"kot_id": 11,
"kot_list": [
{
"price": 55,
"quantity": 1
}
]
},
{
"kot_id": 11,
"kot_list": [
{
"price": 250,
"quantity": 3
},
]
}
]
}
]
EXPECTED RESULT
result = [
{
order_id: 1,
list: [
{
kot_id: 10,
kot_list : [
{ price: 200,quantity: 2 },
{price: 100,quantity: 1},
{price: 150,quantity: 1}
]
},
{
kot_id: 11,
kot_list: [
{price: 55,quantity: 1},
{price: 250,quantity: 3}
]
}
]
}
]