Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create JSON from inputs name and value pairs

I’m working on my personal project and I need a little help. I have a table with some inputs which have name and value attributes. The problem is that I need to create a JSON with pairs name:value.
How do I do something like that with vanilla JS?

My code to print what I have:

// Get all inputs from table and print name and value
document.querySelectorAll("table input").forEach((e) => {
    console.log(e.name, e.value);
});

What I need:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  name1: value1,
  name2: value2,
  name3: value3,
  name4: value4,
}

>Solution :

Start out with an empty object and then, when you’re iterating over the inputs, just assign a new key value pair for that object.

const obj = {}

// Get all inputs from table and print name and value
document.querySelectorAll("input").forEach((e) => {
  obj[e.name] = e.value
})

console.log(obj)
<input name="foo" value="foo">
<input name="bar" value="bar">

Use JSON.stringify(obj) to convert it in to a JSON string if needed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading