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

112
Visualizações
assigning to variable while destructuring in javascript

I have simple question, assume code bellow

const {_id,email}=someVariable
res.json({_id,email})

I want to destructure variable's _id and email in which I can assign them to an object something like bellow code

const {_id,email} as response=someVariable
res.json(response)

How can I do that? As I know, using const{a:b}=someVariable pour value a into b but the same method doesn't work as I want

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

0

You can't do it in a single step, you have to create the object first. Then you can assign to its properties via destructuring:

const response = {};
({_id: response.id, email: response.email} = someVariable);
json.res(response);

const someVariable = {
    _id: 42,
    email: "someone@example.com",
};
const response = {};
({_id: response.id, email: response.email} = someVariable);
console.log(response);

(Note the () around the assignment. That's so the parser doesn't think the { starts a block.)

As you can see, it doesn't do you much (if any) good over something like:

const response = {
    id: someVariable._id,
    email: someVariable.email,
};
res.json(response);

The only thing it really has going for it is that you only reference someVariable once, which could be handy if it's not a simple variable reference (like a function call; but countering that, you could just save the result to a variable).

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