Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 - Possible to destructure from object into another object property? [duplicate]

So I'm trying to figure out if there's any simple ES6 syntax to do the following:

If I have an object

const config = { foo: null, bar: null }

And I want to assign the values of those properties from another object such as:

const source = { hello: "hello", world: "world", another: "lorem", onemore: "ipsum" }

I want to do something like the following but it doesn't work

{ hello:config.foo, world:config.bar } = source

I know I can do something very close like:

{ hello:foo, world:bar } = source

But this creates new variables foo and bar, whereas I want to assign to existing properties on another object. I'm just curious if there's an ES6 shorthand for this; I don't need help doing this with traditional code, I know there are a dozen ways and I already know most of them.

like image 236
T Nguyen Avatar asked Jun 13 '18 18:06

T Nguyen


People also ask

Can you Destructure nested object?

Destructuring nested objectsIf we need to access an employee's info we can destructure as many levels as it takes to get to our employee object's properties. const { engineers: { 1: { id, name, occupation, }, }, } = employees; Now we have access to all of the second employee object's properties.


1 Answers

You're just missing brackets () around the statement.

const config = {};
const source = { hello: "hello", world: "world", another: "lorem", onemore: "ipsum" };
({hello: config.foo, world: config.bar} = source);
console.log(config);
like image 108
baao Avatar answered Sep 25 '22 03:09

baao