Jquery添加重复的数组键

SM帕特

我需要创建一个具有重复键名的 javascript (jquery) 数组,例如下一个

{
    "apple": "type1",
    "apple": "type2",
}

这是我当前使用的代码

var data = {};
jQuery.each(formData, function(i, field) {
    data[field.name] = field.value;
});

在上面的例子field.name"apple"有不同的值,比如"type1"or "type2"

以我目前的代码时,同样field.namejQuery.each我被删除/擦除"apple":"type1"

奥利弗·拉迪尼

这不是 jQuery 问题,而是与 javascript 中对象的性质有关。您不能在同一个键上存储多个值(您将如何访问它们?)。

你可以做的是在一个键上存储一个数组,然后添加:

const formData = jQuery('input');
let data = {};

jQuery('button').click(function() {
  data = {}
  jQuery.each(formData, function(i, field) {
    data[field.name] = data.hasOwnProperty(field.name)
      ? [...data[field.name], field.value]
      : [field.value]
  });
  
  console.dir(data);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="a" />
<input name="b" />
<input name="b" />
<button>Test</button>

上面的代码所做的是对一个键使用一个数组,并为每个项目添加到该数组中。

您可以在没有 jQuery 的情况下执行此操作,也可以在没有 的情况下执行此操作each,您可能会也可能不会喜欢此选项:

const button = document.querySelector('button');
const getAll = selector => Array.prototype.slice.call(
  document.querySelectorAll(selector)
);

let data = {};

button.onclick = () => {
  data = getAll('input')
    .reduce((result, element) => ({
      ...result,
      [element.name]: result.hasOwnProperty(element.name)
        ? [...result[element.name], element.value]
        : [element.value]
    }), {})
    
  console.dir(data)
}
<input name="a" />
<input name="b" />
<input name="b" />
<button>Test</button>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章