This is my array
"status": "Success",
"results": 54,
"orders": [
{
"order_id": 261,
"image": "test1.png",
"productName": "test1",
"price": 2,
"quantity": 2,
"purAmt": 34,
"created_at": "2020-07-27T06:29:32.000Z",
"shopName": "abc"
},
{
"order_id": 261,
"image": "test2.png",
"productName": "test2",
"price": 30,
"quantity": 1,
"purAmt": 34,
"created_at": "2020-07-27T06:29:32.000Z",
"shopName": "abc"
},
]
I want to combine properties with same name and create array of object within a object.
expected output
"status": "Success",
"results": 54,
"orders": [
{
"order_id": 261,
"purAmt": 34,
"created_at": "2020-07-27T06:29:32.000Z",
"shopName": "abc"
products : [
{
"productName": "test1",
"price": 2,
"quantity": 2,
"image": "test1.png",
},
{
"productName": "test2",
"price": 5,
"quantity": 3,
"image": "test2.png",
},
}
]
I would be better if I get the solution using reduce function and without any libraries like lodash
My attempt of doing it using reduce fcn
var result = Object.values(
data.reduce(
(acc, { productName, price, image, quantity, ...rest }) => {
acc[rest.orderID] = acc[rest.orderID] || { ...rest, products: [] };
acc[rest.orderID].products.push({
productName,
price,
image,
quantity,
});
return acc;
},
{},
),
);