Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

311
Visualizações
How to return a default parameter while calling object?

I am using routes variable to return routes to various urls.

export const routes = {
    root: {  path: '/' },
    login: { path: '/login' },
    users: { path: '/users'}
}

Now, I have to use it like routes.login.path now. But is there any way that if nothing is passed after the parameter, it takes 'path' by default. Something like this: routes.login should automatically return '/login'

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You want routes.login to return the string "/login", and you want to access .path through that string. I would recommend you to rethink the the way you are approaching this problem.

Nevertheless, there are two ways to achieve this:

One is to assign a path property onto each string like so:

export const routes = {
    root: Object.assign('/', {  get path() {return String(this)} }),
    login: Object.assign('/login', {  get path() {return String(this)} }),,
    users: Object.assign('/users', {  get path() {return String(this)} }),
}

The other is to override the toString method of the object:

export const routes = {
    root: {  path: '/', toString() {return this.path} },
    login: { path: '/login', toString() {return this.path} },
    users: { path: '/users', toString() {return this.path} }
}

Of course, you can clean this up with a separate class:

// First Method
class Route extends String {
  get path() { return String(this) }
}

export const routes = {
    root: new Route('/'),
    login: new Route('/login'),
    users: new Route('/users')
}

// Second Method
class Route {
  constructor(data) {
    Object.assign(this, data);
  }
  toString() {
    return this.path;
  }
}

export const routes = {
    root: new Route({  path: '/' }),
    login: new Route({ path: '/login' }),
    users: new Route({ path: '/users' })
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda