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
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.
The alternative ['x', 'y'].forEach(prop => oof[prop] = foo[prop]); as I see, is the only one D.R.Y (do not repeat yourself), till now. "DRY" would be indeed useful in the case of several keys to be mapped. You would only need to update one place. Maybe I am wrong. Thanks anyway!
Third example is DRY, but you have to use strings as the keys, which javascript normally does implicitly. Not convinced that's less of a nuisance than: const {x, y} = foo; const oof = {x, y};
Can someone show me in jsfiddle where the first suggestion works? It's not working here on chrome: jsfiddle.net/7mh399ow
@techguy2000 You forgot the semicolon after
var oof = {};
.In the first code, shouldnt be
({x: oof.x, y: oof.y} = foo)
? I think you've put an extra f in oof.