Home > Net >  destructure an object from a function
destructure an object from a function

Time:12-02

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!

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

Show code snippet

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);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related