Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
push multiple objects into an array in javascript

how can i push multiple object into an array

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

this pushes the 1st and 2nd objects, lets say i have 10 files how can i write a line of code to push the 10 objects at once

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

how can i make it one line of code like getting the whole array and push to my database

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could use a forEach on req.files:

req.files.forEach(f => product.photos.push(f.location))
about 4 years ago · Juan Pablo Isaza Report

0

Array.prototype.push() accepts a variable number of arguments. You can spread an array as arguments

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

I'd be inclined to set the photos array within your Product constructor instead

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

const product = new Product(req.files.map(({ location }) => location));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!