jQuery - Create an array of objects using each

idophir picture idophir · Jul 25, 2011 · Viewed 80.1k times · Source

I'm a jQuery newbie.

I have a simple form with n lines (although I'm not using html form):

<div id="myCities">
  <div class="line">City1: <input type="text" /></div>
  <div class="line">City2: <input type="text" /></div>
  <div class="line">City3: <input type="text" /></div>
  <button>Add Your Cities</button>
</div>

I have a javascript var called "users" with general users data:

var users = [
  { "username": "John", "year": 1999},
  more users...
]

When clicking on the button, I want to add an array of cities to the user's data (let's say we are working with John so he's [0])

I want the object to look like:

{ "username": "John",
  "year": 1999,
  "cities": [
    { "City1": $('.line input).val() },
    ... and so on for the 3 cities entered
  ]   
}

I tried using

$.each($('.line'), function() { 
   // but I'm not really sure what to put here 
});

Thanks!

Answer

ShankarSangoli picture ShankarSangoli · Jul 25, 2011

Try this

var cities = [];

var $this, input, text, obj;
$('.line').each(function() { 
   $this = $(this);
   $input = $this.find("input");
   text = $this.text();
   obj = {};
   obj[text] = $input.val();
   cities.push(obj);
});

users[0].cities = cities;