For exemple, i have 3 inputs
<input type="text" name="color" value="blue"/>
<input type="text" name="flavor" value="acid"/>
<input type="text" name="name" value="jack"/>
And a i need get something like this
const obj = {color:'blue', flavor:'acid', name:'jack};
I tried use a for loop, but i get a array, not a object
var obj = [];
var x = document.querySelectorAll('input');
for (var i = 0; i < x.length; i++) {
obj.push(x[i].value)
}
console.log(obj);
You can loop through the values using a
forEach
and update the object.Note: Could also use
reduce
to directly create the objectYou should use a JavaScript object with dynamic property names:
Use JavaScript object instead of an array. To create a object key you just have to declare it between the brackets [ ] and assign a value.