Issues arising when converting multiple JSON array objects into a single object

My first question on this platform! I'm currently learning JavaScript and working on implementing APIs for a college project. I have the API body that passes a JSON object like this:

    [
        {
            "id":1,
            "issueDate":"2021/11/29 09:33",
            "state": "DELIVERED",
            "products": [{"SKUId":12,"description":"a product","price":10.99,"qty":30},
                        {"SKUId":180,"description":"another product","price":11.99,"qty":20},...],
            "supplierId" : 1,
            "transportNote":{"deliveryDate":"2021/12/29"},
            "skuItems" : [{"SKUId":12,"rfid":"12345678901234567890123456789016"},{"SKUId":12,"rfid":"12345678901234567890123456789017"},...]
        },
        ...
    ]

I am facing difficulties in parsing products into an array of product objects.


class Product {

    constructor(SKUId,description,price, qty,) {
        this.id = id;
        this.price = price;
        this.SKUId = SKUId;
        this.qty = qty;
        this.description = description;

    };

}

module.exports = Product;

Here is the code snippet I am using for the parsing:

try {
        if (Object.keys(req.body).length === 0) {
            return res.status(422).json({ error: `Empty body request` }).end();
        }
        
         if (!validate_date(req.body.issueDate) ){
           return res.status(422).json({ error:`Issue Date Not Valid ` }).end();
         }

        if (req.body.products === undefined)
            return res.status(422).json({ error: `Products not defined in the call` }).end();

        if (req.body.supplierId === undefined)
            return res.status(422).json({ error: `SupplierId Not defined` }).end();


        let lastID = await db.getLastIdFromTable('RestockOrder');
        let trID = incrementID(lastID);

      
        let order = new Restock_order(trID, req.body.issueDate, "ISSUED", req.body.supplierId, undefined);
        await db.createRestockOrder(order);

      //THE ISSUE OCCURS HERE
        const products = req.body.products.map((x) => new Product(x.SKUId, x.description, x.price, x.qty));
      
    
  
        order.addProducts(products);
        products.forEach(async (x) => await db.addProductToSKURestockTable(x));
        return res.status(200).end();
    }

Following the line const products = req.body.products.map((x) => new Product(x.SKUId, x.description, x.price, x.qty));, an exception is thrown (handled within a try-catch block), and I'm unable to figure out the root cause of the parsing issue. Appreciate any help in resolving this problem. Thank you!

Answer №1

It appears that there is an issue with the validity of your class product, and the constructor should ideally begin from the id parameter.

const products = req.body.products.map((x) => new Product(x.id,x.SKUId,... and so on

class Product {
  id: number;
  price: number;
  qty: number;
  description: string;
  SKUId:number;
  constructor(id:number,SKUId:number,description:string,price:number, qty:number) {
      this.id = id;
      this.price = price;
      this.SKUId = SKUId;
      this.qty = qty;
      this.description = description;
  };
}

Answer №2

There is no need to include the .products part when you call request.body since you are already within the array.

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

When querying a JSON array of objects in Greenplum PXF external table, an empty string is returned instead of the desired element

When accessing JSON data through an external table using the PXF JSON plugin in a multiline JSON table example, If we define the column as: "coordinates.values[0]" INTEGER, We can easily retrieve 8 from the JSON below: "coordinates":{ "type":"Poin ...

Stuck on an endless loop of the Ionic splash screen

Currently, I am facing an issue with my Ionic 1 project. Everything was functioning properly until a few days ago when the splash screen stopped disappearing on iOS, although it still does on Android. I have searched for solutions on Google but haven' ...

Having trouble parsing JSON data when trying to create a user login with Flutter and PHP

Seeking assistance as I am encountering an issue while developing a user login system using Flutter with a PHP backend. The error message I'm facing is: "type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type &apo ...

Is it possible for me to trigger a custom event using an eventBus listener?

In the Vue component, I have the following setup: data: function() { return { quotes: [] }; }, created() { eventBus.$on("quoteWasAdded", message => { this.quotes.push(message); this.$emit("quotesWereUpdated", this.quot ...

Developing a Swift-based application for blogging

Currently in the process of developing a blog application for a website, I'm intrigued by the various approaches that others are taking. An essential aspect of this project involves working with JSON data containing specific fields such as Title, Date ...

Transfer information from a Vue function to an external JSON document

I would like to store the data for my Vue project in an external JSON file instead of within the Vue function itself. I attempted to retrieve data from an external file using the code below, but encountered issues, possibly due to a conflict with the "ite ...

Executing an asynchronous task without pausing for the outcome

In my Node.js / Express project, there are times when I need to run an asynchronous task that isn't crucial and doesn't require waiting for the outcome, like saving data in an analytics platform: router.post("/", function (req, res, next) { ...

Tips for retrieving the key of a Firebase Object

I'm looking for a way to retrieve the key of a Firebase object without relying on snapshot data. After some investigation, I used the following code: var ref = new Firebase('https://johnsoncompany.firebaseio.com/people') var firstPerson = ...

Is object equality compromised when using track by with ngOptions in AngularJS 1.4 migration?

Seeking assistance to clarify an issue that arose after transitioning from Angular 1.3 to Angular 1.4. I have prepared a JSFiddle demo to showcase this problem. Explanation In my controller, there are two instances of MyElement in a list that a user can ...

Creating an intelligent autocomplete feature in JavaScript that recognizes the . character as a wildcard for matching any character

I found this code and would like to enhance its functionality. For instance, when I search for ".an.d", I want the code to display all words that have an "a" at the second position, "n" at the third position, any character at the fourth position, and "d" ...

Issues concerning placing an item on the card

When I click the "Add a Card" button to add a card to the in-box list, the card becomes sortable between different lists. This functionality works correctly. However, an issue arises when attempting to drag an item from the member list and drop it onto the ...

I am interested in creating JSON data

Below is the provided json data: { "id": 0, "isLeaf": false, "name": "root", "children": [ { "id": 3, "isLeaf": false, "name": "Node 2", "pid": 0, "disabled": true }, { "id": "new5", "isLeaf": ...

What is the best method for obtaining a spring controller's object using AJAX?

Here is the AJAX call I am working with: var url = "UsersGroupReader.html?selectedCompanyName=" + selectedCompanyName + "&test="+Math.random(); req.onreadystatechange = processAccessGroupRequest; req.open("GET", url, true); req.send(null); function ...

Reset the bootstrapvalidator for a specific modal form

Is there a way to reset only the bootstrapValidator errors on a form without removing all data from the input fields? I want to retain the data in the form but just remove the validation errors. Using $('#form').bootstrapValidator('resetForm ...

What is the best way to deserialize a JSON array containing various data types?

While working with JSON, I encountered a situation where an array in the data could contain either strings or integers. How can I successfully parse this data? { "id": "abc", "values": [1,2,3] }, { "id": "def", "values": ["elephant", "toma ...

Ensure the text area box is validated upon clicking a specific radio button

Hello, my HTML code looks something like this: <input type="radio" name='answer_value1[<?php echo $survey1->id?>]' value="<?php echo $answer1->id?>" validate="required:true" id="<?php $answer1->valdt == '1' ? ...

Storing data on the server for your Cocos2d JavaScript game

I've been struggling with implementing a savegame option for my cocos2d JavaScript game. After following a tutorial from Ray Wenderlich (thanks, Ray!), I gave up on trying to do it client-side and am now looking into saving XML files to a web server w ...

Setting up Quasar plugins without using Quasar CLI: A step-by-step guide

I integrated Quasar into my existing Vue CLI project by running vue add quasar. Now I'm attempting to utilize the Loading plugin, but unfortunately, it's not functioning as expected. Here is the configuration setup for Quasar/Vue that I have in ...

Using jQuery to modify the CSS of a div located outside of an iframe

Currently, I am developing a straightforward script. Firstly, here is all of the code that I have: <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script type="text/javascript"> function SuperWebF1() { $("#outerd ...

Is it possible to animate share buttons using Framer Motion but staggering siblings?

I have a Share Icon that looks like: I'm looking to display the first 5 icons, with the 5th icon being the share icon. The remaining icons should appear below the share icon and expand to the right when someone taps or hovers over it (either tap or h ...