JQuery - create an array of objects using each

I am new to jQuery.

I have a simple form with n lines (although I do not use an 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 shared user data:

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

When I click on the button, I want to add a data array to the user data (let's say we work with John so that he [0])

I want the object to look like this:

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

I tried to use

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

Thanks!

+8
jquery object each
source share
2 answers

try it

 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; 
+19
source share
 $.each($('.line'), function() { var key = $(this).text().replace(/.*(City\d+).*/,'$1'); user.cities[key] = $(this).find('input').val(); }); 
+3
source share

All Articles