I'm trying to build a JSON array through a loop where the input className and value will be used as JSON obj and key. But I cannot create one and can't find information on how to create one. I have given a sample below and I need help in the commented line and I want the console.log(json_array); to return {"class_1":"val_1", "class_2":"val_2", "class_3":"val_3", "class_4":"val_4", "class_5":"val_5"}. How can I generate JSON array like this? Also is it even possible to make a JSON array through this method?
document.querySelector("button").onclick = function() {
var json_array = [];
document.querySelectorAll("div input").forEach(x => {
json_array.push(x.className.toString() : x.value.toString()); // DOESN'T WORK
});
console.log(json_array);
};
<html>
<head>
<meta charset="UTF-8">
<title>TEST</title>
</head>
<body>
<div>
<input type="text" class="class_1" value="val_1">
<input type="text" class="class_2" value="val_2">
<input type="text" class="class_3" value="val_3">
<input type="text" class="class_4" value="val_4">
<input type="text" class="class_5" value="val_5">
</div>
<button>BUILD</button>
</body>
</html>
{"class_1", "val_1", "class_2",is invalid syntax. Objects need key-value pairs. An array is not the same thing as an object. If you want an array (values only, no key-value pairs), use an array instead of an object.:to a comma to push multiple items to an array in a single.pushjson_array.push({ name: x.className.toString(), value: x.value.toString() });