Creating JavaScript objects in loop

advertisements

i have been trying to create objects inside a loop. Below is my code.

<div class="container">
<div class="personDetails">
<input type="text" class="abc" id="Name1">
<input type="text" class="abc" id="Age1">
</div>
<br /><br />
<div class="personDetails">
<input type="text" class="abc" id="Name2">
<input type="text" class="abc" id="Age2">
</div>
<button onclick="getDetails()">Check Value</button>
</div>

And below is the javascript..

function getDetails(){
var myObj = {};
$('.personDetails').each(function(){
        $(this).children().each(function(){
myObj[$(this).attr('id')] = $(this).val();
            });
    });
console.log(myObj);
}

And below is what it looks like in console. but i dont want it all into one object. what i want is each person should have each object created in that .each loop. i know i m close but cant figure out what i am doing wrong.

Object {Name1: "cfr", Age1: "15", Name2: "fgatat", Age2: "25"}

I want to do like

person1 {Name: "cfr", Age: "15"},
person2 {Name: "fgatat", Age: "25"}


Here is one of possible solutions:

function getDetails(){
  var myObj = [];
  $('.personDetails').each(function() {
        var person = {};
        $(this).children().each(function(){
            person[$(this).attr('id')] = $(this).val();
        });
        myObj.push(person)
    });
   console.log(myObj);
}