How to get a Object from inputs in vanilla javascr

2020-05-05 00:48发布

问题:

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);

回答1:

You can loop through the values using a forEach and update the object.
Note: Could also use reduce to directly create the object

const obj = {};
const inputs = document.querySelectorAll("input");
inputs.forEach(({ name, value }) => {
 obj[name] = value
})

console.log(obj);
<input type="text" name="color" value="blue" />
<input type="text" name="flavor" value="acid" />
<input type="text" name="name" value="jack" />



回答2:

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.

var obj = {};
var x = document.querySelectorAll('input');
for (var i = 0; i < x.length; i++) {
  obj[x[i].name] = x[i].value
}
console.log(obj);
<input type="text" name="color" value="blue"/>
<input type="text" name="flavor" value="acid"/>
<input type="text" name="name" value="jack"/>



回答3:

You should use a JavaScript object with dynamic property names:

var obj = {};
document.querySelectorAll("input").forEach(input => obj[input.name] = input.value);
console.log(obj);
<input type="text" name="color" value="blue" />
<input type="text" name="flavor" value="acid" />
<input type="text" name="name" value="jack" />