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

220
Visualizações
destructure an object from a function

I need some help with return and destructure an object from a function. I want to assign new paras to what ever return from the function.

function someRes() {
const val1 = 1
const val2 = 2
    return {val1, val2}
}

const {val1, val2} = someRes()
const {val3, val4} = someRes()//this returns as undefined

console.log(val1, val2)
console.log(val3, val4) //console.log undefined

I understand that destructure a params is not like assign them to new params but still, Im looking for an elegant way to do it.

thank!

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

0

You can use aliases during destructuring. When you use destructuring syntax, the variables created assumes the same name as the corresponding object properties. You can change that using the : while destructuring :

function someRes() {
  const val1 = 1
  const val2 = 2
  return {
    val1,
    val2
  }
}

const {
  val1,
  val2
} = someRes()
const {
  val1: val3,
  val2: val4
} = someRes() 

console.log(val1, val2)
console.log(val3, val4)

about 4 years ago · Juan Pablo Isaza Relatório

0

someRes returns an object with two properties val1 and val2. Object destructuring requires that you access properties by name so {val3, val4} returns undefined because the object doesn't have those properties.

It looks like you might want to return a tuple instead of an object from your function. Array destructuring is by index so naming is not constrained by property name.

function someRes() {
  const val1 = 1;
  const val2 = 2;

  return [val1, val2];
}

const [val1, val2] = someRes();
const [val3, val4] = someRes();

console.log(val1, val2);
console.log(val3, val4);

Otherwise you can alias the second destructuring assignment as mentioned in the other answer

function someRes() {
  const val1 = 1;
  const val2 = 2;

  return {val1, val2};
}

const {val1, val2} = someRes();
const {val1: val3, val2: val4} = someRes();

console.log(val1, val2);
console.log(val3, val4);

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