-4

I have a config object like this

{ config: {
    params: {
        football: {
            url: ''
        },
        soccer: {
            url: ''
        }
    }
}

I simply need to get at the football or soccer url value using a variable, so something like

let sport = 'soccer';

let path = config.params.`sport`.url;

I've tried bracket notation like config.params[sport] and the eval function but neither seem to do the trick. I'm sure I'm misnaming what I'm trying to do which is likely why I can't seem to find an answer.

thanks

yoyoma
  • 3,336
  • 6
  • 27
  • 42
  • What is the output of config.params['soccer'] ? – Prasheel Jan 16 '19 at 07:07
  • `config.params[sport]` — You forgot the *variable* name at the front. You need to access the object before you can access the `config` property within it. – Quentin Jan 16 '19 at 07:08
  • Its either football or soccer, sport isn't defined. If you want to use 'sport' variable as a look up then its config.params[sport].url – SPlatten Jan 16 '19 at 07:08
  • 1
    @SPlatten — `let sport = 'soccer';` – Quentin Jan 16 '19 at 07:08
  • @Quentin, Yes, ty, see my edit. – SPlatten Jan 16 '19 at 07:09
  • @SPlatten — Quote: "I've tried bracket notation like config.params[sport]" – Quentin Jan 16 '19 at 07:10
  • "I've tried bracket notation like `config.params[sport]`" it should be `rootObjVariableName.config.params[sport].url`. where `const rootObjVariableName = { config: {...}}` – Yury Tarabanko Jan 16 '19 at 07:10
  • Or to keep reference schema consistent, use: variable['config']['params'][sport]['url'] – SPlatten Jan 16 '19 at 07:11
  • @SPlatten — That's slow to type and hard to read. It's consistant to use dot notation for static references and square bracket notation when you need to use a variable (i.e. using syntax to highlight when you are using a variable) – Quentin Jan 16 '19 at 07:14

1 Answers1

0

This should give you an idea.

const sport = 'soccer'
const data = {
  config: {
    params: {
      football: {
        url: '1'
      },
      soccer: {
        url: '2'
      }
    }
  }
}

console.log(data.config.params[sport].url)
holydragon
  • 6,158
  • 6
  • 39
  • 62
  • thx i'm not sure what happened - I swear I tried it like this but was getting undefined - maybe different compilation error but it works now (wish I could delete this) :) – yoyoma Jan 16 '19 at 09:56