如何映射每个 div 中的输入以使用 Javascript 创建哈希数组

How to map inputs inside each div to create array of hash using Javascript

我有HTML如下

<div class="link-field">
  <div class="form-group assets-form">
    <input type="text" name="description" id="description" class="assets-input" placeholder="For example, Youtube Link">
    <input type="text" name="link" id="link" class="assets-input" placeholder="For example, https://www.youtube.com/">
  </div>

  <div class="form-group assets-form">
    <input type="text" name="description" id="description" class="assets-input" placeholder="For example, Youtube Link">
    <input type="text" name="link" id="link" class="assets-input" placeholder="For example, https://www.youtube.com/">
  </div>
</div>

我尝试遍历每个资产表单并创建如下对象

[
  {
    "link": "http://google.com/one",
    "description": "Link One"
  },
  {
    "link": "http://google.com/two",
    "description": "Link Two"
  }
]

使用以下函数

$.map($('.assets-form'), function(field) {
  console.log(field)
});

在这里我无法在遍历每个 div

后构造哈希

表单完成后即可启动地图功能

在我的示例中,我添加了一个按钮,在输入完成后必须单击该按钮 您可以通过 $(field).find({fieldSelector})

恢复字段值

function mapField() {
  let links = [];
  links = $.map($('.assets-form'), function(field) {
    return {
      link:$(field).find('#link').val(),
      description:$(field).find('#description').val(),
    }
  });

  console.log(links);
}
<div class="link-field">
  <div class="form-group assets-form">
    <input type="text" name="description" id="description" class="assets-input" placeholder="For example, Youtube Link">
    <input type="text" name="link" id="link" class="assets-input" placeholder="For example, https://www.youtube.com/">
  </div>

  <div class="form-group assets-form">
    <input type="text" name="description" id="description" class="assets-input" placeholder="For example, Youtube Link">
    <input type="text" name="link" id="link" class="assets-input" placeholder="For example, https://www.youtube.com/">
  </div>
</div>
<button onclick="mapField()">map field</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>