Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!