Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use an expression in the Object literal key?

I have a switch^

  let s = "aaa"

  switch (true) {
    case s.includes('a'):
      url = 'https://a.com/wp-admin/post-new.php'
      console.log(url)
      break
    case s.includes('b'):
      url = 'https://b.com/wp-admin/post-new.php'
      console.log(url)
      break
    default:
      console.log('default')
      break
  }

I’m trying to change this to a literal object, but I can’t figure out how to properly specify the s.includes condition as the object key

  const objLit = (s) => {
    const cases = {
      //s.includes('a'): 'https://a.com/wp-admin/post-new.php',
      [`${s.includes('a')}`]: 'https://a.com/wp-admin/post-new.php',
      //s.includes('b'): 'https://b.com/wp-admin/post-new.php',
      [`${s.includes('b')}`]: 'https://b.com/wp-admin/post-new.php',
    }

    let url = cases[s]
    return url

  }

  console.log(objLit(s))

Although this does not throw an error, it does not work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t. Property names are strings or Symbols.

When you use [] syntax, the expression is evaluated at object creation time.

You can’t assign code that gets evaluated at lookup time. This is what switch and if/else are for.

In your case, since includes() returns a boolean, you are just creating an object with properties named "true" and "false".

You could say let url = cases.true, but it would be a horrible hack.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading