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
You can return the destructured object in an arrow function, and use Object.assign() to assign it to a variable.
You can just use restructuring for that like this:
Or merge both objects if oof has values:
No, destructuring does not support member expressions in shorthands but only plain propertynames at the current time. There have been talks about such on esdiscuss, but no proposals will make it into ES6.
You might be able to use
Object.assign
however - if you don't need all own properties, you still can doI came up with this method:
Which you can use like this:
i.e., you can pick which properties you want out and put them into a new object. Unlike
_.pick
you can also rename them at the same time.If you want to copy the props onto an existing object, just set the
dest
arg.DRY
or
IMO this is the easiest way to accomplish what you're looking for:
Basically, destructure into variables and then use the initializer shorthand to make a new object. No need for
Object.assign
I think this is the most readable way, anyways. You can hereby select the exact props out of
someObject
that you want. If you have an existing object you just want to merge the props into, do something like this:Another, arguably cleaner, way to write it is:
I use this for
POST
requests a lot where I only need a few pieces of discrete data. But, I agree there should be a one liner for doing this.