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

169
Visualizações
Use JS Proxy to get nested form element

I want to make accessing my form elements easier in JS. Forms have the property 'elements' that gives you access to all the DOM inputs. This allows to get elements either by their position or their DOM name.

This becomes cumbersome however when using arrays in the input name:

<input name='shipping[address][city]' />
const shippingCity = form.elements['shipping[address][city]'];

It would be much nicer to access it with dot notation:

const inputs = new Proxy(form.elements, {
  get(target, handler) { 
    ...
  }
}
const shippingCity = inputs.shipping.address.city;

I'm guessing theres a way to do this with JS proxies. I've found examples on how to access nested data in an object but this needs to build the string from the properties instead, then return the DOM at the top level proxy. I'm guessing this would take 2 seperate proxy handlers.

TLDR: Turn X -> Y

inputs.shipping.address.city -> form.elements['shipping[address][city]']
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I can offer you a solution which works like this, but I warn you it's overwhelmingly hacky. It has to wrap every object property with a proxy, and I wouldn't trust it not to create property name collisions which would be horrible to debug.

const subAccessor = (obj, base, path) => new Proxy(obj, {
    get: (target, prop) => {
        const newPath = `${path}[${prop}]`;
        const obj = base[newPath];
        if (target[prop]) return target[prop];
        return subAccessor(obj || {}, base, newPath);
    }
});

const inputs = new Proxy(form.elements, {
    get: (target, prop) => {
        return subAccessor(target[prop] || {}, target, prop);
    }
});

That's code is a truly awful solution, though, so I strongly recommend that you instead use a simple helper function such as

// usage: `getInput('shipping.address.city')`
const getInput = path => form.elements[
    path.split('.')
    .map((part, i) => i > 0 ? `[${part}]` : part)
    .join('')
];
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