gpt4 book ai didi

javascript - 使用循环将输入转换为数组中的对象

转载 作者:行者123 更新时间:2023-11-28 14:53:05 24 4
gpt4 key购买 nike

我该如何转动它

 <input class="optionsGraph" name="name1" value="value1">
<input class="optionsGraph" name="name2" value="value2">
<input class="optionsGraph" name="name3" value="value3">
<input class="optionsGraph" name="name4" value="value4">
<input class="optionsGraph" name="name5" value="value5">

进入这个(带有循环)?

var example = [
{ label: "name1", y: value1, x: 1 },
{ label: "name2", y: value2, x: 2 },
{ label: "name3", y: value3, x: 3 },
{ label: "name4", y: value4, x: 4 },
{ label: "name5", y: value5, x: 5 }
];

我正在考虑这样的事情?

$(".optionsGraph").each(function(key) {
//another loop

});

我真的很苦恼

最佳答案

您可以使用.map().get()

一起使用

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

var arr = $('.optionsGraph').map(function(index) {
return {
label: $(this).attr('name'), //Get attribute
y: $(this).val(), //Get elements value
x: index + 1
}
}).get();

console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="optionsGraph" name="name1" value="value1">
<input class="optionsGraph" name="name2" value="value2">
<input class="optionsGraph" name="name3" value="value3">
<input class="optionsGraph" name="name4" value="value4">
<input class="optionsGraph" name="name5" value="value5">

关于javascript - 使用循环将输入转换为数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43870766/

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