It is not possible to add items to an array

Attempting to retrieve data from the database using the callback method "getAllOrdersByUserId". The output is displayed below:

[ TextRow {
    DishOrderId: 163,
    BagId: 'BPZDXT68148',
    DateCreated: 2021-05-27T03:55:05.000Z,
    Bags:
     '[{"DishId":43,"DishName":"Kuchvi Biryani","Spicy":2,"UnitPrice":"6.99","Qty":5,"DishTotal":"34.95"}]',
    },
  TextRow {
    DishOrderId: 162,
    BagId: 'BNJENZ08608',
    DateCreated: 2021-05-27T03:46:26.000Z,
    Bags:
     '[{"DishId":41,"DishName":"Dum Biryani","Spicy":2,"UnitPrice":"6.99","Qty":5,"DishTotal":"34.95"}, {"DishId":42,"DishName":"Tysoon Biryani","Spicy":2,"UnitPrice":"6.99","Qty":5,"DishTotal":"34.95"}',
    } ]

Desiring to extract certain attributes from the above results in addition to "Bags". However, the challenge lies in fetching the URL for the image of the dishes, as it is not specified in "Bags". This requires parsing "Bags" and iterating through a loop to obtain the "DishId" that will be used to retrieve the URLs of the images from another method called getDishesByDishIds. The extracted DishIds are as follows:

[43]

[41, 42]

Executing the method getDishesByDishIds would yield the following results for the respective dish Ids when processed in loops:

[ TextRow {
    DishId: 43,
   
    DishImageUrl1:
     'http://192.168.86.104:1111/images/dishImageUrl1_1602546024189.JPG'
 } ]

 [ TextRow {
    DishId: 41,
    DishImageUrl1:
     'http://192.168.86.104:1111/images/dishImageUrl1_1602546024190.JPG'
 },
  TextRow {
    DishId: 42,
    DishImageUrl1:
     'http://192.168.86.104:1111/images/dishImageUrl1_1602546024191.JPG'
} ]

Encountering difficulty in achieving the desired outcome as shown below. The main issue is the inability to include the URLs in the final result as depicted:

{
    "success": 1,
    "bag": [
        {
            "DishOrderId": 163,
            "BagId": "BPZDXT68148",
            "DateCreated": "2021-05-27T03:55:05.000Z",
            "Bags": [
                {
                    "DishId": 43,
                    "DishName": "Kuchvi Biryani",
                    "Spicy": 2,
                    "UnitPrice": "6.99",
                    "Qty": 5,
                    "DishTotal": "34.95"
                }
            ],
            "Url": ['http://192.168.86.104:1111/images/dishImageUrl1_1602546024189.JPG']
        },
        {
            "DishOrderId": 162,
            "BagId": "BNJENZ08608",
            "DateCreated": "2021-05-27T03:46:26.000Z",
            "Bags": [
                {
                    "DishId": 41,
                    "DishName": "Dum Biryani",
                    "Spicy": 2,
                    "UnitPrice": "6.99",
                    "Qty": 5,
                    "DishTotal": "34.95"
                },
                {
                    "DishId": 42,
                    "DishName": "Tysoon Biryani",
                    "Spicy": 2,
                    "UnitPrice": "6.99",
                    "Qty": 5,
                    "DishTotal": "34.95"
                }
            ],
            "Url": ['http://192.168.86.104:1111/images/dishImageUrl1_1602546024190.JPG',
                    'http://192.168.86.104:1111/images/dishImageUrl1_1602546024191.JPG']
        }
    ]
}

The comprehensive code is provided below:

 myOrders: (req, res) => {
    const userId = req.body.userId;
    orderStatus = 2;
    getAllOrdersByUserId(userId, orderStatus, (error, results) => {
      if (error) {
        console.log(error);
        return res.status(500).json({
          success: 0,
          message: "Some other error",
          error: error,
        });
      }
      if (!results) {
        return res.status(404).json({
          success: 0,
          message: "Record not found",
        });
      } else{
        const myOrderArray = []; //this will be new array to store all details including dish Urls
        console.log(results);
        count = 0;
      for (i = 0; i < results.length; i++) { 
        const myOrder = {}
        myOrder.DishOrderId = results[i].DishOrderId;
        myOrder.BagId = results[i].BagId;
        myOrder.DateCreated = results[i].DateCreated;
        myOrder.Bags = JSON.parse(results[i].Bags);
        myOrderArray.push(myOrder);

        OrderDishes = JSON.parse(results[i].Bags);
        //for each one of dish in order dishes get the dish id
        let dishId = []
        DishUrls = [];
        countz = 0;
        for (j = 0; j < OrderDishes.length; j++) {
          dishId.push(OrderDishes[j].DishId);

                  //fetch image url for the dish Id fetched
                  //DishUrls = [];
                  getDishesByDishIds(dishId, (error, getDishesByDishIdsResults) => {
                    if (error) {
                      console.log(error);
                      return res.status(500).json({
                        success: 0,
                        message: "Some other error",
                        error: error,
                      });
                    }
                  
                  console.log(getDishesByDishIdsResults); 
                 // DishUrls = [];
                  count2 = 0;
                  for (l = 0; l < getDishesByDishIdsResults.length; l++) {
                    count2++;
                    if(getDishesByDishIdsResults[l].DishImageUrl1 == undefined){
                      if(count2 == getDishesByDishIdsResults.length){
                        //proceed with other steps
                        console.log(DishUrls);
                      }
                    }
                    else{
                      DishUrls.push(getDishesByDishIdsResults[l].DishImageUrl1);                      
                    }
                  }
                });

          countz ++;
          if(countz == OrderDishes.length){
            //do next step
             console.log(DishUrls);
             myOrder.Url = DishUrls; //not working  , coming incorrect
          }
        }   
      }
      
      return res.json({
        success: 1,
        bag: myOrderArray,
       });

      }
   
    });
  },
};

Apologies for the lengthy post, but any assistance provided will be greatly appreciated as I have been stuck on this issue for a few days.

Answer №1

Important Notice

Please bear with me... This code was written in the late hours of the night after an exhausting day at the office...

I have serious doubts about the reliability of this code. It has not been tested properly and is quite poorly written. It might not even function as intended.

However...

I do hope that it can at least point you in the right direction.

Improved Code

myOrders: (req, res) => {
    const userId = req.body.userId;
    let orderStatus = 2;

    getAllOrdersByUserId(userId, orderStatus, (error, results) => {
        if (error) {
            console.log(error);
            res.status(500).json({
                success: 0,
                message: "Another error occurred",
                error: error,
            });

            return;
        }

        if (!results) {
            res.status(404).json({
                success: 0,
                message: "Record not found",
            });

            return;
        }

        for (let i = 0; i < results.length; i++) {
            
            (() => {
                let currentOrder = results[i];
                currentOrder.Bags = JSON.parse(currentOrder.Bags);

                return new Promise((resolve, reject) => {
                    let dishIds = [];

                    for (let j = 0; j < currentOrder.Bags.length; j++) {
                        dishIds.push(currentOrder.Bags[j].DishId);
                    }

                    (() => {
                        return new Promise((innerResolve, innerReject) => {
                            getDishesByDishIds(dishIds, (error, getDishesByDishIdsResults) => {
                                let dishUrlResults = [];

                                if (error) {
                                    innerReject("An error occurred during retrieval of the dish image urls");
                                    return;
                                }
                
                                for (let l = 0; l < getDishesByDishIdsResults.length; l++) {
                                    if (getDishesByDishIdsResults[l].DishImageUrl1 != undefined) {
                                        dishUrlResults.push(getDishesByDishIdsResults[l].DishImageUrl1);
                                    }
                                }

                                innerResolve(dishUrlResults);
                            });
                        });
                    })()
                    .then((urlResults) => {
                        currentOrder.Url = urlResults;
                        resolve();
                    })
                    .catch((innerPromiseError) => {
                        reject(innerPromiseError);
                    });
                });
            })()
            .then(() => {
                res.json({
                    success: 1,
                    bag: results,
                });
            })
            .catch((promiseError) => {
                //Could not complete the request
                console.log(promiseError);

                res.status(500).json({
                    success: 0,
                    message: "Another error occurred",
                    error: error,
                });
            });
        }
    });
}

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

Adjust the value based on selection

I aim to display another div when either the Full Time or Part Time option is selected. Additionally, I would like to calculate a different value for each option; if 'Part Time' is chosen, PrcA should change to PrcB. Here is the code snippet tha ...

Guidance on dividing children in an object into distinct arrays

So I have an interesting challenge while working on my project. I need help figuring out how to split a Javascript Object like the one below: { field1: { field2: { field3: "value 1", field4: "value 2" ...

comparing values in an array with jquery

I am attempting to retrieve the phone number and mobile number from an array using jquery. jQuery: var data = $('#PhoneLabel').text(); var array = data.split(', '); $.grep(array, function (item, index) { if (item.charAt(0) === &ap ...

Switching Tabs When a Button is Clicked

I am currently using a guide from the link provided to learn how to create tabs: http://www.w3schools.com/howto/howto_js_tabs.asp. function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClass ...

When a form is submitted, it causes NodeJs to return an undefined URL segment

My issue involves setting up a form submission where the URL turns into undefined. Here's the current view: http://localhost:3000/dashboard/tours/categories router.get('/tours/categories', function (req, res) { res.render('agents/t ...

Diagnosing circular JSON can be a challenging task

Encountering an issue in my error handler with the following message: Uncaught TypeError: Converting circular structure to JSON. I suspect that there might be an additional exception thrown within the JSON.stringify call leading to this error. It's p ...

The jsx file is not being parsed by Webpack

In my current project, I am working with a JSX file that contains React code. import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { render () { return <p> Hello React!</p>; ...

Determining When to Activate Button Based on Angular - Verifying That All Choices Have Been Ch

This quiz application requires the user to choose options before proceeding to the next page, with the next button being disabled by default. Once all options are chosen, the next button should become enabled. NOTE: Although the functionality for selecti ...

The compatibility issue between Bootstrap4 Navbar and "jQuery.BgSwitcher" is causing functionality limitations on mobile devices

Currently, I am utilizing Bootswatch4 within Bootstrap4 and have a requirement for a div with backgrounds that change or fade. After some research, I stumbled upon a JavaScript solution that aligns closely with my needs at: https://github.com/rewish/jquery ...

Aggregate information from an array containing multiple nested arrays

With regards to marking this as answered by another question, please take note that this is not a flat array but an array of arrays. Additionally, the numbers provided are just examples for visual representation. I am attempting to iterate through an arra ...

What exactly happens behind the scenes when utilizing the React hook useEffect()? Is an effect set up with useEffect able to halt the main thread

According to the documentation for the useEffect() hook in React, it states that: "Effects scheduled with useEffect don’t prevent the browser from updating the screen." Insight Unlike componentDidMount or componentDidUpdate, effects set with ...

Changing a PDF file into binary form using Node JS and Express

I have a web application that allows users to upload PDF files. Once uploaded, the file needs to be converted into binary data in the backend without being saved in a temporary folder, so it can be stored in a database. While I am able to upload and read ...

Utilize styled-components in next.js to import and resize .svg files seamlessly

I have been attempting to import .svg files into my next.js project, but I have not had any success. I tried importing the .svg files the same way as in my React project by creating a typing.d.ts file and importing the svg as a component. However, it did ...

Develop an Angular JS directive to create a date input with three separate fields, all

Looking for assistance in creating an Angular-js Directive to manage a three-field date input, I am in need of a directive that addresses the issue described in the following link, http://plnkr.co/edit/lHffXV7xEda0xYorucMe?p=preview I have attempted a f ...

Tips for making nested sliding divs within a parent sliding div

Is it possible to slide a float type div inside another div like this example, but with a white box containing "apple" text sliding inside the black div it's in? I have attempted to recreate the effect using this example. Here is my current JavaScript ...

Tips for Retrieving Information from Firebase in an Angular Application

I am facing an issue with my code where the ngFor directive is not working as expected when I use read_CheckOuts to return data from the database. Below are snippets of my code: crud.service.ts import { AngularFireDatabase} from '@angular/fire/datab ...

The Datalist feature in HTML5 offers an auto-suggest functionality that displays a list of options beginning with the

In my project, I am utilizing HTML5 Datalist for autosuggestion. By default, HTML5 follows the keyword contains approach rather than the starts with approach. For example, if my datalist includes one, two, three and I type "o" in the search box, it displ ...

Is Node.js Better with a Framework or Without?

I'm a newcomer to Node.js and eager to learn it from the ground up. I have a project in mind for a social media advertising web app, similar to Myspace rather than Facebook. It will start small but has potential for growth. My main question is whethe ...

Setting the result of d3.csv into a globally accessible variable

Is there a way to store the data fetched from a csv file using d3.csv() in a global variable for future use? I'm facing an issue where the global variable dataset is showing as undefined even after assigning it inside the d3.csv() function. var datas ...

Troubleshooting: Issue with selecting items in jQuery Datatables

While attempting to construct a jQuery datatable using a data object, I encountered an issue. The table is displayed correctly, but the selection feature within the datatable is not functioning as intended. My expectation was that when a row is selected, i ...