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,
}
>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.