Can the props in a destructuring assignment be transformed in place?

心不动则不痛 提交于 2019-12-10 13:32:37

问题


This works…

const { prop1:val1, prop2:val2 ) = req.query
val1 = val1.toLowerCase()

Though, I'm more inclined to do something like

const { prop1.toLowerCase():val1, prop2:val2 } = req.query

or

const { prop1:val1.toLowerCase(), prop2:val2 } = req.query

neither of which work. Is there a syntax similar to this or must manipulations be done outside of the destructing assignment?


回答1:


No, this is not possible. A destructuring assignment does only assign, it does not do arbitrary transformations on the value. (Setters are an exception, but they would only complicate this).

I would recommend to write

const { prop1, prop2:val2 ) = req.query;
const val1 = prop1.toLowerCase();

or, in one statement:

const { prop1, prop2:val2 ) = req.query, val1 = prop1.toLowerCase();



回答2:


The trouble with the temporary variable solutions is that they introduce different versions of the same data into the scope, which can lead to bugs.

This solution creates a utility function that receives the object to be destructured as well as a second object that is a mapping of property names to transformation functions. It's a little more verbose, but does the trick.

// Utility functions to perform specified transformations on an object
function transformProps(obj, trans) {
  return Object.assign({}, obj, ...Object.entries(trans).map(([prop, fn]) => 
    prop in obj ? {[prop]: fn(obj[prop])} : null
  ));
}

const { prop1:val1, prop2:val2 } = transformProps(
  {prop1: "FOO", prop2: "BAR"},
  {prop1: v => v.toLowerCase()} // Transformations to be made
);

console.log(val1, val2);


来源:https://stackoverflow.com/questions/49088003/can-the-props-in-a-destructuring-assignment-be-transformed-in-place

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!