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

217
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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