Warm tip: This article is reproduced from stackoverflow.com, please click
ecmascript-6 javascript destructuring

Is it possible to destructure onto an existing object? (Javascript ES6)

发布于 2020-03-27 10:17:01

For example if I have two objects:

var foo = {
  x: "bar",
  y: "baz"
}

and

var oof = {}

and I wanted to transfer the x and y values from foo to oof. Is there a way to do that using the es6 destructuring syntax?

perhaps something like:

oof{x,y} = foo
Questioner
majorBummer
Viewed
97
loganfsmyth 2018-09-08 01:22

While ugly and a bit repetitive, you can do

({x: oof.x, y: oof.y} = foo);

which will read the two values of the foo object, and write them to their respective locations on the oof object.

Personally I'd still rather read

oof.x = foo.x;
oof.y = foo.y;

or

['x', 'y'].forEach(prop => oof[prop] = foo[prop]);

though.