4

I'm using the Object destructuring syntax of ES6. I want to use it in order to populate an existing object.

I got two objects:

let $scope = {};
let email = { from: 'cyril@so.com', to: 'you@so.com', ... };

I want to assign some email object properties to the $scope object.

For now, I've end up doing so:

({ from: $scope.from, to: $scope.to } = email);

In my real life use case I have more than two properties to be assigned.

So, do you know an other way to improve and avoid repeating the $scope in the left assignation part?

Cyril F
  • 1,842
  • 2
  • 19
  • 35
  • 1
    Uh, oh! Posting my question just made me though about the `Object.assign()` method.. I guess that doing ```$scope = Object.assign($scope, email);``` should do the trick. Well, well, well, posting a question is always useful, isn't it? ;) – Cyril F Feb 08 '16 at 02:32

1 Answers1

1

You are correct, you can do this:

Object.assign($scope, email);

However that is not immutable, you are actually altering the $scope object (which is fine in your case). If you want an immutable operation do this:

$scope = Object.assign({}, $scope, email);

That will return a brand new object.

Also, if you have the Object Rest Spread feature turned on in your transpiler, then you can do this:

$scope = { ...$scope, ...email };

This is also immutable and uses Object.assign behind the scenes.

Tim Kindberg
  • 3,605
  • 1
  • 25
  • 26
  • Oh yes, I didn't though about the Object Rest Spread in this case. I'll stick to the Object.assign, still more 'human readable' I guess. Thanks for your answer! – Cyril F Feb 08 '16 at 02:43