3

I want an associative array object of the string of an HTML element's name to the hidden input element. Like so...

var fieldNames2inputElements = {
    'FirstName' : document.getElementsByName('FirstName')[0],
    'LastName'  : document.getElementsByName('LastName')[0],
    ...
};

I'm already shaking my head at myself, knowing there's got to be a more DRY way of doing this. Any suggestions? How do I use the string key of an associative array as a parameter of something in the value for that key?

BTW: I don't have control of the hidden input elements having this name attribute versus an id or some other way of selecting it.

1
  • The least you touch the DOM the better as per performance. Hence you should do only two document.querySelectorAll() operations, one for each firstname and lastname. Then using Array.prototype.map.call(firstNames, c => {...}); and then the same for the lastNames is one way of doing this job. Commented Apr 10, 2016 at 1:20

3 Answers 3

5

You could define a helper function that accepts name of the target elements and returns an object:

function getByName(names) {
   return names.reduce(function(ret, name) {
       ret[name] = document.querySelector('input[name="'+ name +'"]');
       return ret;
   }, {});
}

var fieldNames2inputElements = getByName(['FirstName', 'lastName', '...']);
Sign up to request clarification or add additional context in comments.

Comments

1

I would write (with es6 arrow functions):

var fieldNames2inputElements = ['FirstName', 'LastName']
  .reduce((o, name) => (o[name] = document.getElementsByName(name)[0], o), {});

Comments

0

You can use a for loop, document.querySelectorAll() with selector "input[name$=Name][type=hidden]" as parameter

for (var i = 0, elems = document.querySelectorAll("input[name$=Name][type=hidden]")
     , fieldNames2inputElements = {}
     ; i < elems.length; i++) {
  fieldNames2inputElements[elems[i].name] = elems[i]
};
console.log(fieldNames2inputElements)
<input name="FirstName" type="hidden" />
<input name="LastName" type="hidden" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.