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

132
Visualizações
How to destructure and reassign in one line using JavaScript

I have an object adData and I need to extract some of it's properties, add some more properties to the extracted object and pass the object as parameter. I can do this using:

const params = {}; 
params.id = adData.id;  
params.status = adData.status; 
params.frequency = adData.frequency; 
params.user = getLoggedInUser(); 
callAnotherFunction(params)

Can I do the destructing and reassigning to new object in one line ? Something like:

const params = {id, status, frequency} = adData; 
params.user = getLoggedInUser(); 

Or

const params = {id, status, frequency, getLoggedInUser(): user} = adData; 

Now these both above syntaxes are wrong but is there any other way to do it using destructuring and without extracting the properties one by one

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you know what properties the object does have, and there aren't that many, you can list them and use rest syntax to gather the others into an object:

const { unwantedProp, ...params) = adData;
// use params

Otherwise, there isn't any incredibly simple syntax for what you want, though you could

const params = Object.fromEntries(
  Object.entries(adData).filter(([key]) => 
    ['id', 'status', 'frequency'].includes(key)
  )
);
about 4 years ago · Juan Pablo Isaza Relatório

0

We can do in one line with destructuring and arrow function.

const getLoggedInUser = () => "foo";
const adData = {
  id: 123,
  status: "active",
  frequency: "less",
  bar: 4,
};

const params = (({ id, status, frequency }, user = getLoggedInUser()) => ({
  id,
  status,
  frequency,
  user,
}))(adData);

console.log({ params });

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