This is my json
let obj = [{
"_id" : "WER12345",
"date" : "2022-07-24",
"totalproduct" : 6,
"productlist" : [
{
"product" : "iphone 13",
"price" : 1000
},
{
"product" : "iphone 12",
"price" : 800
},
{
"product" : "iphone 11",
"price" : 600
},
{
"product" : "iphone 12",
"price" : 800
},
{
"product" : "iphone 13",
"price" : 1000
},
{
"product" : "iphone 12",
"price" : 800
}
] },{
"_id" : "WER98763",
"date" : "2022-07-24",
"totalproduct" : 4,
"productlist" : [
{
"product" : "iphone 13",
"price" : 1000
},
{
"product" : "iphone 11",
"price" : 600
},
{
"product" : "iphone 11",
"price" : 600
},
{
"product" : "iphone 12",
"price" : 800
}
]}]
how to get this from above json in Nodejs and send to frontend reactjs
enter image description here
"_id" : "WER12345",
"date" : "2022-07-24",
"totalproduct" : 6,
"productlist" : [
{
"product" : "iphone 13",
"price" : 2000
},
{
"product" : "iphone 12",
"price" : 2400
},
{
"product" : "iphone 11",
"price" : 600
}
] },{
"_id" : "WER98763",
"date" : "2022-07-24",
"totalproduct" : 4,
"productlist" : [
{
"product" : "iphone 13",
"price" : 1000
},
{
"product" : "iphone 11",
"price" : 1200
},
{
"product" : "iphone 12",
"price" : 800
}
]}]
3
Answers
We have to group productlist by product property.
Here is code for the same.
We can take an temp object and with key as product name and value as price. Then we can iterate through prodcuctlist and add the prices of respective product in temp object.
You can use reduce to achieve this.