Describing the Problem: I am facing a challenge with flattening an array of sales data. Each element in the array contains an ID, sale code, seller username, timestamp, and details which include an array of products, quantities, and subtotals for each item sold. For instance, the original array structure looks like this:
[
{
"_id":"63182596a51be828aa351daf",
"saleCode":1,
"sellerUsername":"rosittog",
"details":
[
{
"product":"3",
"quantity":1,
"paymentType":"cash",
"subtotal":23,
"_id":"63182596a51be828aa351db0"
},
{
"product":"4",
"quantity":1,
"paymentType":"cash",
"subtotal":55,
"_id":"63182596a51be828aa351db1"
}
],
"timestamp":"2022-09-07T05:01:10.462Z",
"__v":0
},
// Additional sales entries...
]
The objective is to flatten this multi-dimensional array into a simplified structure like below:
[
{
"_id":"63182596a51be828aa351db0",
"associatedSaleId":"63182596a51be828aa351daf",
"saleCode":1,
"sellerUsername":"rosittog",
"product":"3",
"quantity":1,
"paymentType":"cash",
"subtotal":23,
"timestamp":"2022-09-07T05:01:10.462Z"
},
// Additional flattened entries...
]
To achieve this transformation, I have implemented the following function:
const flattenSales = function (sales) {
let flatSalesArray = [];
for (const sale of sales) {
let flatSaleEntry = {
_id:'',
associatedSaleId:'',
saleCode:0,
sellerUsername:'',
product:0,
quantity:0,
paymentType:'',
subtotal:0
};
flatSaleEntry.associatedSaleId = sale._id;
flatSaleEntry.saleCode = sale.saleCode;
flatSaleEntry.sellerUsername = sale.sellerUsername;
flatSaleEntry.timestamp = sale.timestamp;
for (const detailItem of sale.details) {
flatSaleEntry._id = detailItem._id;
flatSaleEntry.product = detailItem.product;
flatSaleEntry.quantity = detailItem.quantity;
flatSaleEntry.paymentType = detailItem.paymentType;
flatSaleEntry.subtotal = detailItem.subtotal
flatSalesArray.push(flatSaleEntry);
}
}
return flatSalesArray;
}
Above are previous iterations that did not provide the expected outcome.
The output currently generated displays:
[
{
"_id":"63182596a51be828aa351db1",
"associatedSaleId":"63182596a51be828aa351daf",
"saleCode":1,
"sellerUsername":"rosittog",
"product":"4",
"quantity":1,
"paymentType":"cash",
"subtotal":55,
"timestamp":"2022-09-07T05:01:10.462Z"
}
// Missing third entry due to duplication issue...
]
Analyzed console log indicates the repetition of the last updated data instead of adding unique entries.
If assistance is needed, below includes the calling function within the Express and Mongoose framework context:
router.route('/flattenSales').get( async(req, res) => {
try {
const sales = await Sale.find();
const flattenedSales = await flattenSales(sales);
const sellers = await Seller.find({type: "seller"});
const products = await Product.find();
const accounts = await Accounts.findById("unique");
return res.json({
"flattenedSales":flattenedSales,
"sellers":sellers,
"products":products,
"accounts":accounts
});
}
catch(err) {
console.log(err);
return res.status(400).json('Error: ' + err);
}
})