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?

103 thoughts on “How to return a destructured object without declaring variable from a function?”

Leave a Comment