0

I would like to create an object from variables where the keys are the variable names, and the values are the variable values:

let username = "foo";
let password = "bar";

let request = {
    username: username,
    password: password
};

Resulting value of request:

{"username":"foo","password":"bar"}

Can this be done more simply, without writing username or password or any other variable name twice per object attribute?

5
  • 4
    let request = {username, password} not supported in old crappy browsers tho. Commented Jul 31, 2019 at 13:05
  • Really... I remember trying it a while ago, didn't work.. Commented Jul 31, 2019 at 13:06
  • which browser are you using? Commented Jul 31, 2019 at 13:08
  • Works in latest Chrome, Firefox and MsEdge. Rest I do not bother trying. Commented Jul 31, 2019 at 13:08
  • Tried it... works. Commented Jul 31, 2019 at 13:11

1 Answer 1

3

ECMAScript 6 introduced shorthand property notation, which created a property with the key as the name of the variable, and the value as the value of the variable. It works like so:

let request = { username, password };

This will not work in older, less well-supported browsers however - Internet Explorer is (unfortunately) a good example.

To transpile it, you could use Babel, a popular transpiler.

Sign up to request clarification or add additional context in comments.

2 Comments

FYI: Using babel transpiler solves the old browser support problem
Yeah, I know @aslantorret - but if you don't have, want or need Babel, it's easiest to know which features are supported and which aren't.

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.