Reputation: 42798
I am iterating over an table to pick out the form elements from each table row. What am I doing wrong in the below example?
var result = new Array();
var counter = 1;
$('tbody tr', this.el).each(function(){
var inner = new Array();
$('input',this).each(function(){
console.log(this.name, $(this).val()); // Works: sends name/value to console!
inner[this.name] = $(this).val(); // Appears to be empty
});
result[counter] = inner;
counter++;
});
console.log(result);
Upvotes: 3
Views: 339
Reputation:
Do not initiate object variable inside a loop put it before the loop to improve the performance.
Good luck!!
Upvotes: 0
Reputation: 385405
You're doing arrays wrong.
In Javascript, an Array is a special case of object which has numeric keys only and has an interface defined by functions like push
:
var myArray = [];
myArray.push("first element");
myArray.push("second element");
myArray.push("third element");
You're making the very common mistake of trying to use an array like a more generic object, assigning string keys and using x[y] = z
notation in order to do so. It's a hack that sometimes may happen to seem to work, but is not how arrays are supposed to be used.
You have the same problem with inner
and with result
.
Instead, use the generic object that you were attempting to use in the first place:
var result = {}; // <!-- create new _object_
var counter = 1;
$('tbody tr', this.el).each(function() {
var inner = {}; // <!-- create new _object_
$('input', this).each(function() {
var val = this.value;
console.log(this.name, val);
inner[this.name] = val;
});
result[counter] = inner;
counter++;
});
console.log(result);
Upvotes: 2
Reputation: 15115
Try this:
var result = new Array();
var counter = 1;
var inctr = 0;
$('tbody tr', this.el).each(function(){
var inner = new Array();
inctr = 0;
$('input',this).each(function(){
console.log(this.name, $(this).val()); // Works: sends name/value to console!
inctr++;
inner[inctr] = $(this).val(); // Appears to be empty
});
result[counter] = inner;
counter++;
});
console.log(result);
Upvotes: 0
Reputation: 30185
use
var inner = {};
instead of
var inner = new Array();
than iterate with for-in
statement
also for the results
should be the same, or use results.push()
but in this case counter
not need to be used because of index is set automatically
Upvotes: 0