Reputation: 31
I am trying to update my code to es6.
I updated all my other code to es6 syntax except this part.
I understand the main concept of destructuring (maybe?),
but I don't know how to do destructuring on this code (const userData
part).
I'd like to make this code cleaner.
$scope.doRegister = (registerForm) => {
const userData = {
emailAddress: $scope.registerData.email,
password: $scope.registerData.password,
firstName: $scope.registerData.first,
lastName: $scope.registerData.last
};
userService.registerUser(userData)
.then((userData) => {
$ionicHistory.nextViewOptions({ historyRoot: true });
$state.go('app.deviceSetup');
})
.catch((err) => {
console.error(err);
});
}
Upvotes: 1
Views: 1382
Reputation:
You are essentially trying to "destructure" $scope.registerData
into a new object, userData
. But destructuring only supports destructuring into variables, not objects. Therefore, you could write:
const {
email: emailAddress,
password,
first: firstName,
last: lastName
} = $scope.registerData;
const userData = {emailAddress, password, firstName, lastName};
The first line above is destructuring; the second line uses "shorthand property notation" to build the new object.
There have been proposals, and many questions here on SO, about how to destructure into a new object, but there is no easy, obvious way to do it. The closest you can come is probably using object rest syntax, which will work only if you know what properties you want to omit, will not allow renaming, will create extra variables dontNeed1
etc., and may or may not have native browser support.
const {...userData, dontNeed1, dontNeed2} = ...$scope.registerData;
It is certainly a viable option in this case, or perhaps even preferable, not to try to use destructuring at all, and/or to use @BrianMcCutchon's approach.
Upvotes: 3
Reputation: 8584
I don't think destructuring is the right way to do this. However, there are other ways you can clean up this code. The simplest is to save $scope.registerData
to a temporary variable:
const rd = $scope.registerData
const userData = {
emailAddress: rd.email,
password: rd.password,
firstName: rd.first,
lastName: rd.last
};
Don't get me wrong, you could use destructuring, but you'd end up having to duplicate field names somewhere. This is cleaner.
Upvotes: 3