如何从相关的 form-element 中创建、收集和编程(每个 form-element 一个条目)聚合 objects?

How does one create, collect and programmatically (one entry per form-element) aggregate objects from related form-elements?

我想根据 parent <div>

的 children 中的数据 objects 进行分组

这是我的代码:

<form id="myForm">
  <div id="parent-div">
    <div>
      <input type="text" style="margin: 0;" name="t-name-1" value="value1" />
      <span>
        <input type="text" name="t-quantity-1" value="1" />
        <input type="text" name="t-frequency-1" value="6" />
      </span>
    </div>
    <div>
      <input type="text" style="margin: 0;" name="t-name-2" value="value2" />
      <span>
        <input type="text" name="t-quantity-2" value="2" />
        <input type="text" name="t-frequency-2" value="8" />
      </span>
    </div>
  </div>
  <button type="submit">
    Submit
  </button>
</form>
var group = [];

$('#myForm').on('submit', function(e){
e.preventDefault();
    var elements = document.getElementById("myForm").elements;
  
  for(var i = 0 ; i < elements.length - 1 ; i++){
        var item = elements.item(i);
        //console.log(i, item.name, '-', item.value);
        
        if(item.name.includes(item.name.split("-")[2])){
            var obj = {};
          var name = item.name.split("-")[1];
          obj[ name ] = item.value
                    group.push(obj);
        }
    }
    
    console.log(group);
});

我得到的输出是:

[{
  name: "value1"
}, {
  quantity: "1"
}, {
  frequency: "6"
}, {
  name: "value2"
}, {
  quantity: "2"
}, {
  frequency: "8"
}]

期望的输出:

var group = [
  {
    "name": "value1",
    "quantity": "1",
    "frequency": "6"
  },
  {
    "name": "value2",
    "quantity": "2",
    "frequency": "8"
  }
]

这是一个有效的 jsFiddle:https://jsfiddle.net/7yxzpsd5/45/

最灵活的方法是不对表单的内部 DOM 层次结构做任何假设。相反,它将关注所有表单元素的 name 属性共有的命名模式,即 ... "t-<key>-<id>".

因此,完全 DOM 结构不可知但部分可重用的方法将是二分法/双折法。

  • 第一部分确实介绍了用于识别任何表单元素的正则表达式。此正则表达式如下... /^t-(?<key>\w+)-(?<id>\d+)$/。它具有 named groups for capturing 一个 name 值的 keyid 部分。实际任务...

    • 转换表单元素集合into an array

    • filter 都是有效的(根据正则表达式)表单元素。

    • reduces将过滤后的数组转化为dataItems

      的列表
    • reducer 函数获取正则表达式作为配置对象的一部分,该配置对象也作为 initial value 传递给 reduce

  • 第二个任务是作为通用和可重复使用的函数实现的,它在表单元素的提取 id 以及该元素的提取 [=] 上创建和存储 dataItem 对象16=] 及其 value.

function collectDataItemsByElementKeyAndId(collector, elmNode) {
  const { regX, list, map } = collector;
  const { key, id } = regX.exec(elmNode.name)?.groups ?? {};

  let dataItem = map[id];
  if (!dataItem) {

    dataItem = map[id] = {};
    list.push(dataItem);
  }
  Object.assign(dataItem, { [key]: elmNode.value });
  
  return collector;
}

function handleSubmit(evt) {
  evt.preventDefault();

  const regXKeyAndId = /^t-(?<key>\w+)-(?<id>\d+)$/;

  const dataItemList = Array
    .from(this.elements) // `this` refers to the form element.

    .filter(elm => regXKeyAndId.test(elm.name))
    .reduce(collectDataItemsByElementKeyAndId, {

      regX: regXKeyAndId,
      map: {},
      list: [],

    }).list;

  console.log({ dataItemList });
}

$('#myForm').on('submit', handleSubmit);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="myForm">
  <div id="parent-div">
    <div>
      <input type="text" style="margin: 0;" name="t-name-1" value="value1" />
      <span>
        <input type="text" name="t-quantity-1" value="1" />
        <input type="text" name="t-frequency-1" value="6" />
      </span>
    </div>
    <div>
      <input type="text" style="margin: 0;" name="t-name-2" value="value2" />
      <span>
        <input type="text" name="t-quantity-2" value="2" />
        <input type="text" name="t-frequency-2" value="8" />
      </span>
    </div>
  </div>
  <button type="submit">
    Submit
  </button>
</form>

$('#myForm').on('submit', function(e) {
  e.preventDefault();
  var divs = document.querySelectorAll('#myForm > #parent-div > div')
  var group = []

  divs.forEach(div => {
    var inputs = div.querySelectorAll('input')
    var obj = {}

    inputs.forEach(i => {
      var name = i.getAttribute('name').split('-')[1]
      obj[name] = i.value
    })

    group.push(obj)
  })

  console.log(group)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
  <div id="parent-div">
    <div>
      <input type="text" style="margin: 0;" name="t-name-1" value="value1" />
      <span>
        <input type="text" name="t-quantity-1" value="1" />
        <input type="text" name="t-frequency-1" value="6" />
      </span>
    </div>
    <div>
      <input type="text" style="margin: 0;" name="t-name-2" value="value2" />
      <span>
        <input type="text" name="t-quantity-2" value="2" />
        <input type="text" name="t-frequency-2" value="8" />
      </span>
    </div>
  </div>
  <button type="submit">
    Submit
  </button>
</form>