jQuery - 使用每个对象创建一个对象数组

ido*_*hir 11 each jquery object

我是一个jQuery新手.

我有一个简单的形式有n行(虽然我没有使用HTML格式):

<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>
Run Code Online (Sandbox Code Playgroud)

我有一个名为"users"的javascript var,包含一般用户数据:

var users = [
  { "username": "John", "year": 1999},
  more users...
]
Run Code Online (Sandbox Code Playgroud)

当点击按钮时,我想在用户的数据中添加一系列城市(假设我们正在与John合作,所以他是[0])

我希望对象看起来像:

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

我试过用

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

谢谢!

Sha*_*oli 28

试试这个

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;
Run Code Online (Sandbox Code Playgroud)


mar*_*arc 5

$.each($('.line'), function() { 
   var key = $(this).text().replace(/.*(City\d+).*/,'$1');
   user.cities[key] = $(this).find('input').val(); 
});
Run Code Online (Sandbox Code Playgroud)