Home > Back-end >  How to create JSON from inputs name and value pairs
How to create JSON from inputs name and value pairs

Time:12-25

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:

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

CodePudding user response:

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.

CodePudding user response:

Here is an alternative approach to achieving the same thing.

const userData = [...document.querySelectorAll("table input")]
  .reduce((obj, {name, value}) => {
    obj[name] = value;
    return obj;
}, {});

console.log(userData);
<table>
  <tr><td> <input name="name" value="Brandon Victors" /> </td></tr>
  <tr><td> <input name="age" value="16" /> </td></tr>
  <tr><td> <input name="country" value="USA" /> </td></tr>
  <tr><td> <input name="state" value="Florida" /> </td></tr>
  <tr><td> <input name="number" value="(123) 456-7890" /> </td></tr>
</table>

  • Related