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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6817369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:24:55  来源:igfitidea点击:

jQuery - Create an array of objects using each

jqueryobjecteach

提问by idophir

I'm a jQuery newbie.

我是一个 jQuery 新手。

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

我有一个包含 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>

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

我有一个名为“用户”的 javascript 变量,其中包含一般用户数据:

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])

单击按钮时,我想向用户数据添加一系列城市(假设我们正在与约翰合作,所以他是 [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!

谢谢!

回答by ShankarSangoli

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;

回答by marc

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