Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

94
Vistas
How can I loop through the keys of an object and set values equal to a destructured variable?

I am trying to simplify and shorten my current code. My code is working fine. This is what I have:

app.patch('/listings/:id', (req, res) => {
    const { id } = req.params;
    console.log(req.body)
    const {
        leaser, propertyType, pricePerDay,
        currency, city, street, description
    } = req.body;
    const foundListing = listings.find(l => l.id === id);
    
    foundListing.leaser = leaser;
    foundListing.pricePerDay = pricePerDay;
    foundListing.propertyType = propertyType;
    foundListing.currency = currency;
    foundListing.city = city;
    foundListing.street = street;
    foundListing.description = description;

    res.redirect('/listings');
})

How can I make the repetitive last half of the code shorter? There is probably a way in which I can write only one line

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I would use the following approach.

app.patch('/listings/:id', (req, res) => {
   const { id } = req.params;
   const foundListing = listings.find(l => l.id === id);

   Object.keys(foundListing).forEach(key => {
     foundListing[key] = req.body[key]
   })

   res.redirect('/listings');
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use Object.assign() in combination with the spread operator to copy the properties of req.body to the foundListing like this:

const foundListing = listings.find(l => l.id === id);
Object.assign(foundListing, ...req.body)

Or even shorter (as you probably don't need the foundListing variable later):

Object.assign(listings.find(l => l.id === id), ...req.body);

Suddenly your code becomes really short:

app.patch('/listings/:id', (req, res) => {
    Object.assign(listings.find(l => l.id === req.params.id), ...req.body);
    res.redirect('/listings');
})

If you want to copy only certain properties of req.body, you could do it like this:

const foundListing = listings.find(l => l.id === id);
["leaser", "pricePerDay", "propertyType", "currency", "city", "street", "description"].forEach((e) => {
  foundListing[e] = req.body[e];
});

about 4 years ago · Juan Pablo Isaza Denunciar

0

If all the foundListing properties are going to be modified, then you could loop through the properties to make changes, like so:

app.patch('/listings/:id', (req, res) => {
    
    const { id } = req.params,
          foundListing = listings.find(l => l.id === id);

    for(const key in foundListing){ 
        foundListing[key] = req.body[key] 
    }

    res.redirect('/listings');
})

If you need to specify which properties are going to be modified then you can list them in an array and loop through them to make changes, like so:

app.patch('/listings/:id', (req, res) => {
    
    const { id } = req.params,
          foundListing = listings.find(l => l.id === id),
          keys = [
             'leaser', 
              'propertyType', 
              'pricePerDay',
              'currency', 
              'city', 
              'street', 
              'description'
          ];

    keys.forEach(key => { foundListing[key] = req.body[key] })
    res.redirect('/listings');
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda