我该怎么转
<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
});
我真的很挣扎这个
答案 0 :(得分:3)
您可以将.map()
与.get()
由于返回值是包含数组的jQuery对象,因此在结果上调用
.get()
以使用基本数组非常常见。
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)
&#13;
<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">
&#13;
答案 1 :(得分:1)
在循环中添加一行。
var output =[];
$(".optionsGraph").each(function(key) {
output.push({label : $(this).attr("name"), y: $(this).val(), x : key+1 );
});
答案 2 :(得分:0)
试试这个:
var res = [], i = 0;
$(".optionsGraph").each(function(key) {
//another loop
res.push({
label: $(this).attr('name'),
y : $(this).val(),
x: ++i
});
});
答案 3 :(得分:0)
纯js解决方案,使用Array#map
。
var elems = document.getElementsByClassName('optionsGraph'),
res = Array.from(elems).map((v,i) => ({label: v.name, y: v.value, x: i+1}));
console.log(res);
<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">
答案 4 :(得分:0)
试试这个Array#push
var example=[]
$(".optionsGraph").each(function(a,b) {
example.push({label:$(this).attr('name'), y:$(this).val(), x: a+1})
});
console.log(example)
&#13;
<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">
&#13;