[英]Javascript stored only the last one from a loop in an JSON Object
I have a HTML Site with 4 inputRange slidern. 我有一个HTML网站,其中包含4个inputRange sliden。 If a user click on a button all the values from the ranges should be stored in a nested JSON Object. 如果用户单击按钮,则范围内的所有值都应存储在嵌套的JSON对象中。 So far so good, but JS only saves the last one in that Array and not the others before. 到目前为止,一切都很好,但是JS仅将最后一个保存在该Array中,而不保存之前的其他数组。 But all Sliders have different values from 1 to 5, but JS saves only the 4 from the last slider. 但是所有Sliders的值从1到5都不同,但是JS仅从最后一个滑块保存4。 Here's my code: 这是我的代码:
//Speichert die aktuellen Angaben in einem Nested-JSON Objekt
function saveBewertung() {
var jsonObj = {};
var kriterien = [];
var bewertungen = {};
//Loop
$('input[type=range]').each(function() {
var id = $(this).attr("id");
var note = $(this).val();
bewertungen.id = id;
bewertungen.note = note;
kriterien.push(bewertungen);
jsonObj.Bewertungen = kriterien;
});
jsonObj.Kommentar = $('textarea#kommentar').val();
//TEST AUSGABE
alert(JSON.stringify(jsonObj));
}
Result: 结果:
You are pushing the same object to the array again and again. 您一次又一次将同一对象推到数组中。 You need to initialize bewertungen
every time in the each
block. 您需要在each
块中每次都初始化bewertungen
。
Declare 宣布
var bewertungen = {};
inside the each
block 在each
块内
$('input[type=range]').each(function() {
var bewertungen = {};
var id = $(this).attr("id");
var note = $(this).val();
bewertungen.id = id;
bewertungen.note = note;
kriterien.push(bewertungen);
});
jsonObj.Bewertungen = kriterien; //this line can be moved out
Another possibility next to the solution from @gurvinder372 is to shorten the function so you don't need to declare the variables bewertungen
, id
and note
: @ gurvinder372解决方案旁边的另一种可能性是缩短功能,因此您无需声明变量bewertungen
, id
和note
:
//Speichert die aktuellen Angaben in einem Nested-JSON Objekt
function saveBewertung() {
var jsonObj = {};
var kriterien = [];
//Loop
$('input[type=range]').each(function() {
// Anonymous object
kriterien.push({
id: $(this).attr("id"),
note: $(this).val()
});
});
jsonObj.Bewertungen = kriterien;
jsonObj.Kommentar = $('textarea#kommentar').val();
//TEST AUSGABE
alert(JSON.stringify(jsonObj));
}
Here is some description how this thing is working 这是一些说明这东西是如何工作的
var bewertungen = {}; // this line declare the object this object will hold values in each loop.
$('input[type=range]').each(function() {
var bewertungen = {};
var id = $(this).attr("id");
var note = $(this).val();
bewertungen.id = id; // this line add value to {bewertungen} object key
bewertungen.note = note; // this line add value to {bewertungen} object key
kriterien.push(bewertungen); // every itration will push value to [kriterien] array
});
jsonObj.Bewertungen = kriterien; // this is final array with all values
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.