skip to Main Content

I want to use an object in nodejs to store url paths, and reuse a previous entry for example:

let URLS = {
  root: "www.example.com",
  paths: {
    user: root + "/user",
    login: root + "/login"
  } 
}

is there a way to achieve this?

2

Answers


  1. You cannot access URLS.root before the object is created, but you can define a separated variable root and use that in multiple places in the URLS object:

    const root = "www.example.com";
    
    const URLS = {
      root,
      paths: {
        user: root + "/user",
        login: root + "/login"
      } 
    }
    
    console.log(URLS)

    In the example above, the root property is defined using a shorthand property names instead of writing the property name and the property value separately (e.g. { root: root }).

    Login or Signup to reply.
  2. You need to slightly modify your code because you can’t directly use root inside the paths object since it’s defined within the URLS object. Instead, you should refer to this.root or URLS.root. Here’s the corrected code:

    let URLS = {
      root: "www.example.com",
      paths: {
        user: URLS.root + "/user",
        login: URLS.root + "/login"
      } 
    };
    
    console.log(URLS.paths.user);
    console.log(URLS.paths.login);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search