【问题标题】:jQuery - Create an array of objects using eachjQuery - 使用每个对象创建一个对象数组
【发布时间】:2011-10-12 15:23:10
【问题描述】:

我是 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>

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

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

单击按钮时,我想将一组城市添加到用户数据中(假设我们正在与 John 合作,所以他是 [0])

我希望对象看起来像:

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

我尝试过使用

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

谢谢!

【问题讨论】:

  • 您想何时将城市列表添加到对象中? John 会单击“保存”或“提交”按钮,还是您需要在他键入时更新它,或者其他什么?
  • 点击“添加您的城市”按钮时。没什么特别的。

标签: jquery object each


【解决方案1】:

试试这个

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;

【讨论】:

  • 你不应该在你的局部变量上使用var吗?
  • 如果我在每个循环中定义它,它们将为不需要的每次迭代定义。出于这个原因,我在循环之外定义了它们。
  • 虽然@marc 的解决方案更加优雅,但我最终还是使用了这个解决方案。我相信它更通用,会对更多人有所帮助。
  • 顺便说一句,在我看来,这只是将对象obj 的引用传递给数组,这意味着对象中的数据会被覆盖......我认为......
  • 它应该是var cities = new Array(); 而不是var cities = [];,因为后者不会让你推送它。错误将显示 .push 不是有效方法。
【解决方案2】:
$.each($('.line'), function() { 
   var key = $(this).text().replace(/.*(City\d+).*/,'$1');
   user.cities[key] = $(this).find('input').val(); 
});

【讨论】:

    猜你喜欢
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2020-03-23
    • 2018-04-14
    • 1970-01-01
    • 2020-12-21
    相关资源
    最近更新 更多