Destructuring in a return statement [duplicate]

我与影子孤独终老i 提交于 2021-01-29 06:14:53

问题


I have multiple cases throughout my app that look something like this:

  getVariables() {
    const {
      allowCustomValues,
      budgets,
      budgetsToAdd,
      budgetsToRemove,
      isGlobal,
      isRequired,
      name,
      tagTypeId,
      valuesToAdd,
      valuesToDelete,
    } = this.props;

    return {
      allowCustomValues,
      budgets,
      budgetsToAdd,
      budgetsToRemove,
      isGlobal,
      isRequired,
      name,
      tagTypeId,
      valuesToAdd,
      valuesToDelete,
    };
  }

This seems very cumbersome, but the shorter solution involves preceding every variable I want with this.props., which isn't really better from a maintenance standpoint.

What I'd like is something like:

  getVariables() {
    return this.props.{
      allowCustomValues,
      budgets,
      budgetsToAdd,
      budgetsToRemove,
      isGlobal,
      isRequired,
      name,
      tagTypeId,
      valuesToAdd,
      valuesToDelete,
    };
  }

Is there some kind of ES6 syntax that allows me to make this code a bit more DRY?

EDIT: Possibly a duplicate of ES6 destructuring within a return statement, but that one has an accepted answer that doesn't solve the problem.


回答1:


Actually destructuring does not allow that.

You are asking about equivalent for lodash's pick(). Maybe you have already lodash in you project. If you don't you still can write such a helper on your own(but better use stable community-proved versio from lodash or another library)




回答2:


Why not just use Object.assign()?

    return Object.assign({}, this.props);

That'll build a new empty object and then copy all the enumerable properties from this.props into it. The target object is returned by Object.assign() so it pretty much does all the work.




回答3:


How about

return {...this.props}



来源:https://stackoverflow.com/questions/63307361/typesscript-destructuring-assignment-destructure-and-assign-the-group-in-parall

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