Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - 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());
question from:https://stackoverflow.com/questions/65918275/how-to-return-a-destructured-object-without-declaring-variable-from-a-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...