0

Say I have the object:

const obj = {
  foo: 'bar'
}

And I assign foo to a variable like so:

let {foo} = obj

Is it possible to change the variable name? I've tried using as like you can with Imports but that doesn't work.

let {foo as bar} = obj

I'm sure I'm missing something obvious but my google-fu is failing me today.

1
  • 2
    let { foo: bar } = obj; :D Basically, LHS syntax is copied from RHS syntax, so no special stuff like as. more destructuring secrets Commented Sep 11, 2018 at 11:02

1 Answer 1

4

The simplest way, if it's just a single property, is not to use destructuring:

let bar = obj.foo;

If you want to use destructuring (perhaps you have several properties), though, give the name of the property, a colon, and the name of the variable/constant:

let {foo: bar} = obj;

Example:

const obj = {
  foo: 'bar'
};
let {foo: bar} = obj;
console.log(bar);

Remember that object destructuring syntax exactly mirrors object initializer syntax. In an object initializer, foo: bar assigns the value from bar to the property foo:

const obj = {foo: bar}; // Property `foo` is assigned the value from variable `bar`

So in object destructuring, foo: bar assigns the value of the property foo to the variable bar:

let {foo: bar} = obj;   // Variable `bar` is assigned the value from property `foo`
Sign up to request clarification or add additional context in comments.

1 Comment

Thats it thanks! I was assigning quite a few variables from an object so destructuring was the cleanest way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.