8

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.

T Nguyen
  • 3,309
  • 2
  • 31
  • 48

1 Answers1

14

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);
baao
  • 71,625
  • 17
  • 143
  • 203