How to return a destructured object without declaring variable from a function?

const obj = {
  '0': '100',
  '1': '0',
  '2': '0'
};

console.log("defaultObj", obj);

const test1 = () => {
  return {
    0: amount,
    1: balance,
    2: products
  } = obj;
};

const test2 = () => {
  const {
    0: amount,
    1: balance,
    2: products
  } = obj;
  return {
    amount,
    balance,
    products
  }
};

console.log("test1", test1());
console.log("test2", test2());

The output is

defaultObj { '0': '100', '1': '0', '2': '0' }
test1 { '0': '100', '1': '0', '2': '0' }
test2 { amount: '100', balance: '0', products: '0' }

So what is the difference between test1 and test2?

How to return a destructured object without declaring them as variables like in test2.

The desired output is to convert test1 output to test2 by returning the destructured object right away

Without declaring them as variables is there a possible solution?

Answer

what is the difference between test1 and test2?

An assignment expression always returns the right hand side value. return (… = obj2) will always return the obj2 value no matter what is.

how to return a destructured object without declaring them as variables?

You seem to be confused about what destructuring does. There is no such thing as a “destructured object”, when you de-structure the object it’s not an object any longer. Its invidivual parts are getting assigned to plain variables.

In your test2 function, you then create a new object with the values from these variables, using an object literal with shorthand syntax.

There is no way to combine a destructuring target and an object literal into one expression.

If you don’t want to introduce individual variables with destructuring (either in the parameter declaration or a separate variable declaration), just access the argument object properties directly as usual:

function test3(obj) {
  return { amount: obj[0], balance: obj[1], products: obj[2] };
}

(Taken from @user3840170’s comment)

Leave a Reply

Your email address will not be published. Required fields are marked *