Say I have an object foo with properties a and b but I want to transfer the values of these properties to another object bar with properties x and y where bar.x
gets the value of foo.a
and bar.y
gets the value of foo.b
.
The first way that comes to mind to accomplish this with ES5 would be like the following.
var foo = { a: 5, b: 17 };
var bar = { x: foo.a, y: foo.b };
This is already pretty terse but having to reference foo
in each case to access it's properties gets noisy for a larger property mapping. Looking in to the new destructuring features in ES6 it seems that it is possible to destructure nested objects into a flattened set of variables but I haven't found any examples which point out the ability to specify an object in which to destructure property values instead. Does this feature not exist or have I just not found the example that shows how this is done? If it is not possible are there any other clever tricks that can be done to achieve a similar result?
To be clear I was hoping to be able to do something along the lines of the example below.
var foo = { a: 5, b: 17 };
var bar = { a: x, b: y } = foo;
This question is different from (One-liner to take some properties from object in ES 6) because I'm looking for a way to avoid writing foo and not the property list. In fact keeping the property list for explicit mapping is my goal.