问题
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