Home > OS >  I have a json object with array object inside, how to access array object and if same product displa
I have a json object with array object inside, how to access array object and if same product displa

Time:07-27

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
    }
]}]

CodePudding user response:

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);
    return { ...jsonResponse, productlist: groupedProductList };
}

CodePudding user response:

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)

CodePudding user response:

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);

CodePudding user response:

Presented below is one possible way to achieve the desired objective.

Code Snippet

const myTransform = obj => ({
  ...obj,
  productlist: Object.entries(
    (obj?.productlist ?? []).reduce(
      (acc, {product, price}) => (
        acc[product] ??= price,
        acc[product]  =  price,
        acc
      ),
      {}
    )
  ).map(([product, price]) => ({ product, price }))
});

/* explanation
// method to transform the array as desired
const myTransform = obj => ({
  ...obj,       // first keep all other props as-is
  productlist: Object.entries(        // transform intermediate results into array
    (obj?.productlist ?? []).reduce(  // generate intermediate result object using "reduce"
      (acc, {product, price}) => (    // "acc" is the accumulator, destructure array elt
        acc[product] ??= price,       // if "product" not already in "acc", set to 0
        acc[product]  =  price,       // add the "price" to acc.product
        acc                     // always return "acc"
      ),
      {}                        // initialize "acc" to empty object
    )
  ).map(            // transform object-entries into desired object array
    ([product, price]) => ({ product, price })
  )
});

*/

const myData = {
  "_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
    }
  ]
};

console.log('transforming data as below:\n', myTransform(myData));
.as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation

Inline comments added to the snippet above.

  • Related