How to get a Object from inputs in vanilla javascript

后端 未结 3 545
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-16 22:35

For exemple, i have 3 inputs





        
相关标签:
3条回答
  • 2021-01-16 23:18

    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" />

    0 讨论(0)
  • 2021-01-16 23:35

    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" />

    0 讨论(0)
  • 2021-01-16 23:35

    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"/>

    0 讨论(0)
提交回复
热议问题