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

182
Visualizações
Overriding object's default getter operator

Let's say I have the following object in my JS code:

var myData = {
  "someWeirdPrefix_name": "John Doe",
  "someWeirdPrefix_age": 24,
  ...
}

Is there a way to override the default getter operator (.)? As in, if I write myData.name, I would like to get "John Doe" (thanks to the override). Basically I want to override the method so that I can take the key given, add the weird prefix to the key and then get the value. I know the easy approach would be to just clean my actual data and remove the prefix, but that's not acceptable in my use case. Is this actually possible to do for every property (not just name and age)?

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

0

Usually Proxy is used for that

const myData = {
  "someWeirdPrefix_name": "John Doe",
  "someWeirdPrefix_age": 24,
}

const newMyData = new Proxy(myData, {
  get(target, prop, receiver) {
    return target['someWeirdPrefix_' + prop];
  }
})

console.log(newMyData.name)

about 4 years ago · Juan Pablo Isaza Relatório

0

I suggest you create a proxy over the data object, and on the get handler, you can check if there is a key in myData including the dot notation key, if YES, get the value of that key.

const myData = {
  "someWeirdPrefix_name": "John Doe",
  "someWeirdPrefix_age": 24,
}

const handler = {
   get(target, prop, receiver) {
    return target[Object.keys(target).find(key => key.includes(prop))]
  }
}

const proxy = new Proxy(myData, handler);

console.log(proxy.name)

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