0

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"}

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Spring how can results.push({[this.id]: this.value}); same with results[this.id] = this.value; ?
apologize havent noticed that , my answer clearly wasn't quite right thumbs ;)
1

use the array [val] to create dynamic computed property (getting value as key ) as below:

also as @uingtea mentiend use for result object {} instead of array []

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

var $actionBtn = $("#action_button");
var results = {};

$actionBtn.on("click", function() {
  $('#main_form input').each(function() {
    results[this.id]= this.value
  });

  var json = JSON.stringify(results);
  console.log(json);
});
<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>


<button id="action_button"> generate</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.