Issue encountered while attempting to utilize the concat method to condense an array

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

})

Answer №1

Here are two modifications you can make to correct your code:

  1. Update the Array#concat method to create a copy of ventaPlana instead of directly referencing it, like so:

    arrayVentasPlano=arrayVentasPlano.concat({...ventaPlana});
    

Additionally, ensure that you move return arrayVentasPlano; outside the outer for loop.

DEMO

const v = [
    {
    "_id":"63182596a51be828aa351daf",
    "codVenta":1,
    "vendedor":"rosittog",
    "detalle":
        [
            {
                "producto":"3",
                "cantidad":1,
                "tipoPago":"efectivo",
                "subtotal":23,
                "_id":"63182596a51be828aa351db0"
                },
            {
                "producto":"4",
                "cantidad":1,
                "tipoPago":"efectivo",
                "subtotal":55,
                "_id":"63182596a51be828aa351db1"
                }
        ],
    "fechaHora":"2022-09-07T05:01:10.462Z",
    "__v":0
    },

    {
        "_id":"631845c706b2c211ed6f5ca9",
        "codVenta":1,
        "vendedor":"rosittog",
        "detalle":
        [
            {
                "producto":"4",
                "cantidad":1,
                "tipoPago":"efectivo",
                "subtotal":55,
                "_id":"631845c706b2c211ed6f5caa"
                }
        ],
        "fechaHora":"2022-09-07T07:18:30.829Z",
        "__v":0
    }
];

const aplanarVentas=function (ventas) {
    let arrayVentasPlano=[];

    for (const venta of ventas) {

        let ventaPlana= {
            _id:'',
            idVentaAsociada:'',
            codVenta:0,
            vendedor:'',
            producto:0,
            cantidad:0,
            tipoPago:'',
            subtotal:0
        };

        ventaPlana.idVentaAsociada=venta._id;
        ventaPlana.codVenta=venta.codVenta;
        ventaPlana.vendedor=venta.vendedor;
        ventaPlana.fechaHora=venta.fechaHora;

        for (const elemDetalle of venta.detalle) {
            ventaPlana._id=elemDetalle._id;
            ventaPlana.producto=elemDetalle.producto;
            ventaPlana.cantidad=elemDetalle.cantidad;
            ventaPlana.tipoPago=elemDetalle.tipoPago;
            ventaPlana.subtotal=elemDetalle.subtotal
            arrayVentasPlano=arrayVentasPlano.concat({...ventaPlana});
        }
    }
    return arrayVentasPlano;
}

console.log( aplanarVentas( v ) );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Dynamic Parameters in NodeJS Route Definitions

I am currently working with a route that has the following structure: app.route('/api/*/*/*') .get(function(req, res){ var entitya = req.params['0']; var entityb = req.params['1']; var entity3 = req.params[' ...

Exploring the contrast between window and document within jQuery

I'm curious about the distinction between document and window in jQuery. These two are commonly utilized, but I haven't quite grasped their differences. ...

Check to see if a name entered by the user matches any of the names saved in the array of

I am in the process of developing a program to compare the salaries of 2 employees. To start, I gather the names of all employees in an array called employeeName and their respective sales figures in an array named AnnualSales. My main obstacle arises when ...

Middleware for automatically populating a Jade variable in all app.get() routes

I have a unique setup with my Jade file system where all templates extend layout.jade. In this main template, I need to include a logout button only when the user is logged in (this information is stored in req.session). So within layout.jade, there will ...

Loop through the v-for based on the input number that was selected

I'm looking to accomplish the following: if a user selects input X (a number between 1 and 10), I want to render a specific vue component X times. It seems to work if I use v-for n in 10, but not when I use variables. <template> <div> ...

Is there a method to retrieve all Class elements without using a for-loop?

I am trying to retrieve all elements with a specific class using document.getElementsByClassName(); <body> <div class="circle" id="red"></div> <div class="circle" id="blue"></div> <div class="circle" id="yell ...

Having trouble accessing a parsed JSON value in Node.js, encountering 1 error

Currently, I am working on creating a simple news web application as a way to practice utilizing APIs. The particular API that I have chosen for this project is . If you take a look at this JSON object that I am attempting to console.log, you will see the ...

Trouble with refreshing button after resolving routes in Angular UI Router

My Angular UI router is giving me trouble. When I navigate to the state below, everything works smoothly. However, if I refresh the page, the resolve function retrieves the data, injects it into the controller, but the view does not load. Essentially, th ...

Nested loops - I'm on the brink of success, but there's a minor flaw in this code

I am currently working on a function that takes two arrays of strings as input from another function. The goal is to compare each element in the first array with every element in the second array and determine if they are equal in length. Let x represent ...

Is it possible to change the name of a PHP file using the value entered in an input

I am currently in the process of trying to change the name of a file while uploading it using the JQuery uploader. I have made some progress, and here is the crucial part of my UploadHandler.php: protected function handle_file_upload($uploaded_file, $name ...

Oops! Looks like there was an issue: TypeError - 'app.use() function needs a middleware'

Recently delving into Node Js, I embarked on a learning journey and attempted the following code. However, it seems to be throwing an error that has left me stumped. Despite searching for solutions, I can't seem to pinpoint what's causing the iss ...

Converting a Complex Array of Objects into a CSV File for Download in a React Application

My current data is available for download in xls/csv format, but when using the react-csv npm package, the name and description are being displayed in the same column instead of separate columns. I am seeking assistance on how to display the data with Nam ...

Strategies for resolving duplicate jQuery code in my project

Trying to simplify my jQuery code that handles video selection and playback functionality. Users can click on a thumbnail or button to play a specific video, with the title of the video changing accordingly. Despite achieving the desired outcome, the cur ...

Verify the Absence of an Internet Connection Through a Popup on a Windows 10 Application Developed in Javascript

Hey there, I've been browsing the web but can't seem to find a comprehensive tutorial on how to write a code that displays an error message when there is no internet connection. I'm currently using Visual Studio to develop a Windows 10 App w ...

AngularJS UI router regular expressions allows for dynamic and flexible routing

I'm attempting to find a parameter with two possible values: 'current' or a number with at least 10 digits. Here's what I've tried: url: '/history/{code:^current$|^[0-9]{10,}$}' Although this regular expression suc ...

Utilize a directive every instance

I need to implement an angular directive that triggers before all events like ng-click whenever the view value changes. This directive should be called as the first action when the view is changed. Check out the JSFiddle example. angular.module('myA ...

Establish a timeout period for ajax requests using jQuery

$.ajax({ url: "test.html", error: function(){ //do something }, success: function(){ //do something } }); At times, the success function performs well, but sometimes it does not. How can I add a timeout to this ajax re ...

Vue Subroutes within nested components do not automatically load

My application features a sidebar that I want to utilize to load the Patient view by default when accessing patient/:id. This should also trigger the loading of the PatientDashboard sub-view. Within the Patient view component, there is a router-view that ...

Find the nearest element with a specific class using jQuery

I am currently using jQuery version 1.12.4 for the purpose of retrieving the value from the closest element with a specific class selector. Unfortunately, I am encountering difficulty in selecting the closest element as desired. $(function() { $("[cla ...

Error in Passport JS: Trying to use an undefined function

I've been struggling with debugging my code in Express and Passport. I've tried following solutions from others but can't seem to get it right. Any help or useful links would be greatly appreciated. Here is the error message along with the ...