Home > Software design >  How to use an expression in the Object literal key?
How to use an expression in the Object literal key?

Time:12-14

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.

CodePudding user response:

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.

  • Related