gpt4 book ai didi

javascript - Jquery添加重复的数组键

转载 作者:行者123 更新时间:2023-12-02 23:28:17 24 4
gpt4 key购买 nike

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

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

这是我当前的代码堆栈

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

在上面的示例中,field.name“apple”,具有不同的值,例如“type1”“type2”.

使用我当前的代码,当 jQuery.each 中的相同 field.name 时,我被删除/删除了 "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>

关于javascript - Jquery添加重复的数组键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56627148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com