How to implement a dynamic key for a property in an object?

  • 0
    Hello everyone!

    There is a conditional object

    export const CONST_NAMES= {
        CONST1: 'constanta 1',
        CONST2: 'constanta 2',
        CONST3: 'constanta 3',
        CONST4: 'constanta 4',

    And there is an object second object:

    export const CONST_NAMES_SORT = {

    When outputting to the console for example:


    We get undefined. Is it possible to make the second object more flexible, where the key will have an "or" condition? Or do you need to paint the whole object?

    Sandbox link
    JavaScript Anonymous, Jun 1, 2020

  • 2 Answers
  • 0
    Do console.log (CONST_NAMES_SORT) and see for yourself.

  • 0
    As I understand it, you want multiple keys to access the same value. If yes, then in zhs, since you cannot get the address of strings, numbers, etc., this is impossible.

    However, if the value is an object or an array, then the reference is passed there, and if you change the values ‚Äč‚Äčinside the object / array, then the reference to them will not change.

    const obj1 = { value: 'Odd' };
    const obj2 = { value: 'Even' };
    export const CONST_NAMES_SORT = {
    [CONST_NAMES.CONST1]: obj1,
    [CONST_NAMES.CONST3]: obj1,
    [CONST_NAMES.CONST2]: obj2,
    [CONST_NAMES.CONST4]: obj2,
    console.log(CONST_NAMES_SORT[CONST_NAMES.CONST3].value); // > Not Odd

    In short, not possible, but there are a couple of exceptions.
    Norah Osborne

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!