1

I tried to create an object and wanted to set some fields by calling other fields. I get error

base: `${this.api.foo.domain}${this.api.foo.port}${this.api.foo.version}`,
                   ^

TypeError: Cannot read property 'foo' of undefined

code:

module.exports = {
    api: {
        foo: {
            domain: 'api.foo.com',
            port: ':8080',
            version: '/v1',
            base: `${this.api.foo.domain}${this.api.foo.port}${this.api.foo.version}`,
            verifyToken: `${this.api.foo.base}/oauth/token/{bearerToken}`,
        }
    }
};

How can I call fields properly?

Malena T
  • 341
  • 2
  • 7
  • 22

1 Answers1

0

this inside of an object literal does not refer to the object, but to the context, which is not defined in this case (as the code is global and not inside of a method). To be able to refer to the objects values, you have to move the property outside of the object and attach it after the object was declared:

const data = {
  api: {
    foo: {
        domain: 'api.foo.com',
        port: ':8080',
        version: '/v1',            
    }
  }
};

data.api.foo.base = `${data.api.foo.domain}${data.api.foo.port}${data.api.foo.version}`;
data.api.foo.verifyToken = `${data.api.foo.base}/oauth/token/{bearerToken}`;

module.exports = data;
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151