将 JSON 数组对象解析为对象的问题

Problems with parsing a JSON array objects into an object

第一个问题我 post 在这里。 我正在学习 js 并尝试为大学项目做一些 APIs。 我有传递 JSON 对象的 API 主体:

    [
        {
            "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"},...]
        },
        ...
    ]

我在将产品解析为产品对象数组时遇到问题。


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;

最后这是我用于解析的代码:

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

      //THIS IS THE LINE OF THE CODE THAT DOESNT WORK
        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();
    }

命令后 const products = req.body.products.map((x) => new Product(x.SKUId, x.description, x.price, x.qty)) ;代码启动异常(在 try-catch 块中捕获),我不知道解析中的真正问题是什么。 感谢所有帮助我解决此问题的人

您的 class 产品无效,构造函数应从 id 参数开始

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

当您调用 request.body 时,您已经在数组中,因此无需添加 .products 部分