Skip to content
Advertisement

Push all inputs ids and values into json array

I am getting an error when I run this code this way…

var action = $("#action_button").html();
var results = [];
    
$('#main_form input').each(function(){
    results.push({
        this.id : this.value
        });
});

var json = JSON.stringify(results);

… but I don’t get the results I want when I execute it this way…

var action = $("#action_button").html();
var results = [];
    
$('#main_form input').each(function(){
    results.push({
        id:this.id
        value: this.value
        });
});

var json = JSON.stringify(results);

I want it to return:

 {id: "22", first_name: "john", last_name: "smith"}

It is currently returning:

 {"id":"id","value":"22"},{"id":"first_name","value":"john"}, 
 {"id":"last_name","value":"smith"}

Advertisement

Answer

.push() is for array [], for object {} use object[key] = value

var results = {}; // <== object
$('#main_form input').each(function() {
  results[this.id] = this.value;
});

console.log(JSON.stringify(results))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="main_form">

id: <input id="id" value="22" /><br>
name: <input id="first_name" value="john" /> <br> 
surname: <input id="last_name" value="smith" /><br>

</form>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement