Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

93
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda