Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Create an array of objects using each

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!

like image 604
idophir Avatar asked Jul 25 '11 14:07

idophir


People also ask

How do you iterate an array of objects in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How do I create an array in jQuery?

Syntax And Declaration:var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"]; Type of Array: The type of an array is “object“. Iteration Approach: We use the length property of the array to iterate in the array.

What is each in jQuery?

The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.

Can we use for loop in jQuery?

You can use a JavaScript for loop to iterate through arrays, and a JavaScript for in loop to iterate through objects. If you are using jQuery you can use either the $. each() method or a for loop to iterate through an array.


2 Answers

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;
like image 161
ShankarSangoli Avatar answered Oct 02 '22 20:10

ShankarSangoli


$.each($('.line'), function() { 
   var key = $(this).text().replace(/.*(City\d+).*/,'$1');
   user.cities[key] = $(this).find('input').val(); 
});
like image 43
marc Avatar answered Oct 02 '22 21:10

marc