将属于某个数组名称的所有输入检索到jquery变量中

时间:2017-03-30 16:54:54

标签: javascript jquery html

假设我有这个html:

<td>
  <input type="hidden" name="params[test][index]" value="0">
  <input type="hidden" name="params[test][name]" value="2">
  <input type="hidden" name="params[other][]" value="0">
  <input type="hidden" name="params[test2]" value="0">
</td>

我想把params数组的所有输入作为数组或json抓到我的jquery中:

(不确定语法,但有类似的东西)

var $params = { test => {index =>0, name=>2},other=>[0],test2=>0}; 

我该怎么办?

1 个答案:

答案 0 :(得分:2)

您可以创建普通对象,使用input迭代$.each()元素,将.split()RegExp一起使用

var params = {};

$.each($("td input"), function(_, el) {
  var param = el.name.split(/^\w+(?=\[)|\[|\]/).filter(Boolean).pop();
  params[param] = el.value;
});

console.log(params);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
  <input type="hidden" name="params[test][index]" value="0">
  <input type="hidden" name="params[test][name]" value="2">
  <input type="hidden" name="params[other][]" value="0">
  <input type="hidden" name="params[test2]" value="0">
</td>
</tr>
</table>

修改,更新

您可以使用ifif..else条件和语句RegExp来解析.name属性,以获得OP中描述的预期结果

var params = {};
var re = /\[|\]/g;

$.each($("td input"), function(_, el) {
  var param = el.name.match(/\[\]|\[\w+\]/g);
  var prop = param.shift().replace(re, "");
  if (param.length) {
    if (!(prop in params) && param[0] !== "[]") {
      params[prop] = {};
    }
    if (prop in params) {
      params[prop][param.shift().replace(re, "")] = el.value;
    } else if (param[0] === "[]") {
      params[prop] = [el.value];
    }
  } else {
    params[prop] = el.value;
  }
});

console.log(params);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<table>
  <tr>
    <td>
      <input type="hidden" name="params[test][index]" value="0">
      <input type="hidden" name="params[test][name]" value="2">
      <input type="hidden" name="params[other][]" value="0">
      <input type="hidden" name="params[test2]" value="0">
    </td>
  </tr>
</table>