skip to Main Content

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


  1. We have to group productlist by product property.

    Here is code for the same.

    const jsonResponse = {
        _id: 'WER12345',
        date: '2022-07-24',
        totalproduct: 4,
        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 },
        ],
    };
    // Below variable has value in asked format
    const jsonResAfterFormatting = transformResponse(jsonResponse);
    function groupProductsByProduct(productList) {
        const products = {};
        productList.forEach(productDetails => {
            if (productDetails.product in products) {
                products[productDetails.product] += productDetails.price;
            } else {
                products[productDetails.product] = productDetails.price;
            }
        });
        const groupedProductList = [];
        for (let product in products) {
            const price = products[product];
            const productDetails = {
                product,
                price,
            };
            groupedProductList.push(productDetails);
        }
        return groupedProductList;
    }
    
    function transformResponse(jsonResponse) {
        const groupedProductList = groupProductsByProduct(jsonResponse.productlist);
        // if "jsonResponse" is a type of array
        
        /*
        const result = []
        jsonResponse.forEach((productElement)=>{
            let groupedProductList = groupProductsByProduct(jsonResponse.productlist);
            result.push({ ...productElement, productlist: groupedProductList })
        }) 
        return res */
        return { ...jsonResponse, productlist: groupedProductList };
    }
    
    Login or Signup to reply.
  2. 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.

    let obj = {
    "_id" : "WER12345",
    "date" : "2022-07-24",
    "totalproduct" : 4,
    "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
        }
    ]
    }
    
    
    let products =obj.productlist;
    let temp_obj = {}
    for(let product of products){
        if(temp_obj[product.product]){
            temp_obj[product.product] =  temp_obj[product.product]  + product.price;
        }else{
             temp_obj[product.product] = product.price;
        }
    }
    
    let keys = Object.keys(temp_obj);
    let values = Object.values(temp_obj);
    let productList = []
    for(let i=0;i<keys.length;i++){
        let obj = {}
        obj['product'] = keys[i];
        obj['price'] = values[i];
        productList.push(obj);
    }
    
    obj.productlist = productList;
    
    console.log(obj)
    
    Login or Signup to reply.
  3. You can use reduce to achieve this.

    let 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
        }
    ];
    
    // create a map of {$product: $accumulatePrice} based on the data in productlist array
    let groupByProduct = productlist.reduce((acc, curr) => {
        if(acc[curr.product]) {
            acc[curr.product] += curr.price;
        } else {
            acc[curr.product] = curr.price;
        }
        return acc;
    },{});
    
    // convert the groupByProduct map into an array of object(your expected format)
    let resList = Object.keys(groupByProduct).map(key => {
        return{
            "product" : key,
            "price" : groupByProduct[key]
        };
    });
    
    console.log(resList);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search