簡體   English   中英

將多個對象推入 javascript 中的數組

[英]push multiple objects into an array in javascript

我如何將多個 object 推入一個數組

router.post(`/products`, upload.array("photos" , 10), async (req, res) => {
  console.log(res);
  try {
    let product = new Product();
    product.photos.push(req.files[0].location);
    product.photos.push(req.files[1].location);
    await product.save();
    console.log(Product);
    res.json({
      status: true,
      message: "save succes",
    });
  } catch (error) {
    console.log(error);
  }
});

這會推送第一個和第二個對象,假設我有 10 個文件,我如何編寫一行代碼來一次推送 10 個對象

  product.photos.push(req.files[0].location);
    product.photos.push(req.files[1].location);

我怎樣才能使它成為一行代碼,例如獲取整個數組並推送到我的數據庫

您可以在req.files上使用forEach

req.files.forEach(f => product.photos.push(f.location))

Array.prototype.push()接受可變數量的 arguments。 您可以將數組傳播為 arguments

product.photos.push(...req.files.map(({ location }) => location));

我傾向於在您的Product構造函數中設置photos數組

class Product {
  constructor(photos = []) {
    this.photos = photos;
  }
}

const product = new Product(req.files.map(({ location }) => location));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM