Home > database >  Destructuring object returned by inline function
Destructuring object returned by inline function

Time:10-12

I need condition while doing destructuring, so I just created this as a function and it works.

const demo = () => {
  if (2 > 1) {
    return {
      a: 'aaa',
      b: 'bbb',
    }
  }
  return {
      a: 'xxx',
      b: 'yyy',
  }
}

const { a, b } = demo()

console.log([a, b]) // will be ['aaa', 'bbb']

But before that I tried to do this as inline function (because I need this logic in single place so I do not see point of making this as named function), without success.

const { a, b } = () => {
  if (2 > 1) {
    return {
      a: 'aaa',
      b: 'bbb',
    }
  }
  return {
      a: 'xxx',
      b: 'yyy',
  }
}

console.log([a, b]) // will be [undefined, undefined]

I know that this does not work because function is not executed - it's trying to destruct from function code and not function result.

But how to do it then?

In this example I could use ternary operator instead function, but in real code my function is more complicated with a lot of conditions etc so it's not possible.

const { a, b } = 2 > 1 ? {
  a: 'aaa',
  b: 'bbb',
} : {
  a: 'xxx',
  b: 'yyy',
}


console.log([a, b]) // will be ['aaa', 'bbb']

CodePudding user response:

Execute function like this:

const { a, b } = (() => {
  if (2 > 1) {
    return {
      a: 'aaa',
      b: 'bbb',
    }
  }
  return {
      a: 'xxx',
      b: 'yyy',
  }
})();

console.log([a, b]) // will be ["aaa", "bbb"]

  • Related