user3541032
user3541032

Reputation: 147

Javascript stored only the last one from a loop in an JSON Object

I have a HTML Site with 4 inputRange slidern. If a user click on a button all the values from the ranges should be stored in a nested JSON Object. So far so good, but JS only saves the last one in that Array and not the others before. But all Sliders have different values from 1 to 5, but JS saves only the 4 from the last slider. 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:

enter image description here

Upvotes: 1

Views: 57

Answers (3)

Mustkeem K
Mustkeem K

Reputation: 8798

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

Upvotes: 0

ahendwh2
ahendwh2

Reputation: 382

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:

//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));
}

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

You are pushing the same object to the array again and again. You need to initialize bewertungen every time in the each block.

Declare

var bewertungen = {};

inside the each block

$('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

Upvotes: 2

Related Questions