skip to Main Content

I have input elements like this:

<input name="fruit" id="fruit" value="Orange">
<input name="vegetable" id="vegetable" value="Spinach">
<input name="dairy" id="dairy" value="Eggs">
<input name="bread" id="bread" value="Bread">
<input name="soup" id="soup" value="Soup">

I need to get them all and create an object like this:

{
  fruit: "Orange", 
  vegetable: "Spinach", 
  dairy: "Eggs", 
  bread: "Bread", 
  soup: "Soup"
}

I created this method but perhaps there may be a better or more efficient and succinct way to achieve this result:

My code:

const inputs = document.getElementsByTagName('input');

function convertToObject(obj){
  let inputString = '';
  for(const input of inputs){
    inputString += `, "${input.id}": "${input.value}"`;
  }
  return JSON.parse(`{${inputString.substring(1).trim()}}`);
}

const objArray = convertToObject(inputs);
console.log(objArray);

4

Answers


  1. The easiest way would probably be to use new FormData if your inputs are contained within a form element:

    const form = document.getElementById("form");
    const formData = new FormData(form);
    console.dir(Object.fromEntries(formData));
    <form id="form">
      <input name="fruit" id="fruit" value="Orange">
      <input name="vegetable" id="vegetable" value="Spinach">
      <input name="dairy" id="dairy" value="Eggs">
      <input name="bread" id="bread" value="Bread">
      <input name="soup" id="soup" value="Soup">
    </form>

    Above, I’m wrapping the form data object in a call to Object.fromEntries() to get an object output, but depending on what you’re trying to do exactly, you may not need to do this, as you can access element’s values simply by doing formData.get("fruit") for example (which gives "Orange"), or even form.fruit.value which doesn’t require the need for the fromData object to be created.


    If you don’t have a form wrapping all of your elements then you can try one of the below options.

    In your example code, building a string first isn’t needed as you can instead build your object directly. This way you can avoid the need to parse your string into an object as you’ll already have one from the beginning. For example:

    const inputs = document.getElementsByTagName('input');
    
    function convertToObject(obj){
      const result = {};
      for(const input of inputs){
        result[input.id] = input.value;
      }
      return result;
    }
    
    const objArray = convertToObject(inputs);
    console.log(objArray);
    <input name="fruit" id="fruit" value="Orange">
    <input name="vegetable" id="vegetable" value="Spinach">
    <input name="dairy" id="dairy" value="Eggs">
    <input name="bread" id="bread" value="Bread">
    <input name="soup" id="soup" value="Soup">

    You can also use other methods to build the object, such as Object.fromEntries() by passing in an array of [key, value] pairs. You can create this array by mapping your HTMLCollection (returned by getElementsByTagName()) to an array containing [key, value] pairs with the help of Array.from()‘s mapping function:

    const inputs = document.getElementsByTagName('input');
    
    function convertToObject(inps){
      return Object.fromEntries(Array.from(inps, elem => [elem.id, elem.value]));
    }
    
    const objArray = convertToObject(inputs);
    console.log(objArray);
    <input name="fruit" id="fruit" value="Orange">
    <input name="vegetable" id="vegetable" value="Spinach">
    <input name="dairy" id="dairy" value="Eggs">
    <input name="bread" id="bread" value="Bread">
    <input name="soup" id="soup" value="Soup">
    Login or Signup to reply.
  2. You can create dynamically an object, you don’t have to built a JSON and parse it :

    const inputs = document.getElementsByTagName('input');
    
    function convertToObject(obj){
      const result = {};
      for(const input of inputs){
        result[input.id] = input.value;
      }
       return result;
    }
    
    const objArray = convertToObject(inputs);
    console.log(objArray);
    <input name="fruit" id="fruit" value="Orange">
    <input name="vegetable" id="vegetable" value="Spinach">
    <input name="dairy" id="dairy" value="Eggs">
    <input name="bread" id="bread" value="Bread">
    <input name="soup" id="soup" value="Soup">
    Login or Signup to reply.
  3. const inputs = document.getElementsByTagName('input');
    
    function convertToObject(objs){
      let result = {};
      for(const input of objs){
        result[input.id] = input.value;
      }
      return result;
    }
    
    const objArray = convertToObject(inputs);
    console.log(objArray);
    
    Login or Signup to reply.
  4. Let’s not forget reduce.

    const inp2Obj =
      [...document.querySelectorAll(`input`)]
        .reduce((acc, obj) => ({ ...acc, [obj.id]: obj.value }), {});
        
    console.log(inp2Obj);
    <input name="fruit" id="fruit" value="Orange">
    <input name="vegetable" id="vegetable" value="Spinach">
    <input name="dairy" id="dairy" value="Eggs">
    <input name="bread" id="bread" value="Bread">
    <input name="soup" id="soup" value="Soup">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search