最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can the props in a destructuring assignment be transformed in place? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Mar 3, 2018 at 19:33 tjfwalker asked Mar 3, 2018 at 18:58 tjfwalkertjfwalker 4944 silver badges18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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 plicate this).

I would remend 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();

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);

发布评论

评论列表(0)

  1. 暂无评论