How to build a json object with a loop?

There is no JSON here. Please don't confuse:

  • A JavaScript object (a data structure)
  • A JavaScript object literal (code to create such a data structure)
  • JSON (a data format based on a subset of object literal notation)

If you want an ordered list of objects (or any other kind of JavaScript data structure) then use an array. Arrays have a push method.

var myData = [];
rows.each(function (index) {
    var obj = { 
        id: $this.find('.elementOne').val(),
        name: $this.find('.elementTwo').text()
    };
    myData.push(obj);
});

You override the object instead of adding it a new value each iteration.

Fixed code using an array:

jsonObj = [];
rows.each(function(index) {
    jsonObj.push({
        'id': $this.find('.elementOne').val(),
        'name': $this.find('.elementTwo').text()
    });
});​

What you want is an array of objects. When you try to write the same property on the same object multiple times, it gets overwritten which is why you're seeing id and name contain values for the last iteration of the loop.

Although you haven't tagged the question with jQuery, it does look like jQuery, so here's a solution:

I've taken the liberty to change $this to this because $this seems to be referring to the same object in each iteration, which is now what you may want (methinks)

var myArray = rows.map(function() {
    return {
        id: $(this).find('.elementOne').val(),
        name: $(this).find('.elementTwo').text()
    };
});