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
The easiest way would probably be to use
new FormData
if your inputs are contained within aform
element: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 doingformData.get("fruit")
for example (which gives"Orange"
), or evenform.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:
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 bygetElementsByTagName()
) to an array containing[key, value]
pairs with the help ofArray.from()
‘s mapping function:You can create dynamically an object, you don’t have to built a JSON and parse it :
Let’s not forget
reduce
.