简体   繁体   中英

Javascript define string constants as shorthand properties

Is there any way to define a string value like a shorthand property, something like eg (this doesn't work):

const dict = {
    USER_LOGIN,
    USER_LOGOUT
};

Which will be equivalent to:

const dict = {
    USER_LOGIN: "USER_LOGIN",
    USER_LOGOUT: "USER_LOGOUT"
};

I want to define a constants dictionary, but I was wondering if I can somehow avoid the repetition pattern MYVALUE : "MYVALUE" .

Is there any shorthand way of declaring object keys with values equivalent to their string values, similar to the (not working) code above?

There's no built-in way to do something like that automatically, but if you want to keep the code DRY, you can make a helper function that, when passed an array of strings, creates an object with those properties:

 const makeDict = arr => arr.reduce((a, str) => ({ ...a, [str]: str }), {}); const dict = makeDict(['USER_LOGIN', 'USER_LOGOUT']); console.log(dict); 

Just kidding:

 let dict; with(new Proxy({}, { get(_, key) { return key; }, has(_, key) { return key !== "dict"; } })) { dict = { USER_LOGIN, USER_LOGOUT }; } console.log(dict); 

If you think that does not work... just try it :)

But seriously: The whole question is just overkill.

You can declare them and use those constants as key-value on an object.

 const USER_LOGIN = "USER_LOGIN"; const USER_LOGOUT = "USER_LOGOUT"; const dict = { USER_LOGIN, USER_LOGOUT }; console.log(dict); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Shorthand property notation will only work when you have a variable having the same name as the property you want to declare:

 const USER_LOGIN = 'USER_LOGIN'; const USER_LOGOUT = 'USER_LOGOUT'; const dict = { USER_LOGIN, USER_LOGOUT }; console.log(dict); 

Otherwise, you have to specify the whole object:

const dict = {
    USER_LOGIN: "USER_LOGIN",
    USER_LOGOUT: "USER_LOGOUT"
};

Or create it via a helper as @CertainPerformance mentionned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM