简体   繁体   中英

Building JSON object out of HTML elements value in javascript

So right now i have the following in my page:

在此处输入图片说明

where it consists of a dropdown menu and an input text field. So what I want is to create a JSON formatted object in javascript from the HTML elements above so I would get something like:

myObj = {
   Name: Jake,
   Address: 51 Lake District
}

However the method I'm using right now is sort of inefficient where i did it like:

var myObj = {
   [document.getElementById("drop1").value]:document.getElementById("n_in").value,
   [document.getElementById("drop2").value]:document.getElementById("a_in").value,
}
console.log(JSON.stringify(myObj))

I'm not entirely sure if this is a good way of doing it, but in the future if i were to add another set of fields like a "Country" dropdown in the HTML, I would have to hard code another field into the variable above again.

Is this a good way of doing it?

 var myObj = { [document.getElementById("drop1").value]:document.getElementById("n_in").value, [document.getElementById("drop2").value]:document.getElementById("a_in").value, } console.log(JSON.stringify(myObj))
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="lst"> <div class = "ifield"> <select id = "drop1"> <option value = "Name">Name</option> </select> <input type = "text" id = "n_in" value = "Jake"> </div> <div class = "ifield"> <select id = "drop2"> <option value = "Address">Address</option> </select> <input type = "text" id = "a_in" value = "51 Lake District"> </div> </div> <script src = "test.js"></script> </body> </body> </html>

You could select all your .ifield elements and reduce() them to an object:

 const values = [...document.querySelectorAll('.ifield')].reduce((a, v) => { a[v.querySelector('select').value] = v.querySelector('input').value; return a; }, {}); console.log(values);
 <div id="lst"> <div class="ifield"> <select id="drop1"> <option value="Name">Name</option> </select> <input type="text" id="n_in" value="Jake"> </div> <div class="ifield"> <select id="drop2"> <option value="Address">Address</option> </select> <input type="text" id="a_in" value="51 Lake District"> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM