Reputation: 1603
I want to create javascript object using .push()
Method and create Key Value Pair
.
I have tried it, but it doesn't work.
$("input[name^=ang_nama]").each(function() {
arr_nama.push($(this).attr('id'):$(this).val());
});
Any solutions?
Upvotes: 3
Views: 2279
Reputation: 1475
Try this, add curly braces while pushing
$("input[name^=ang_nama]").each(function() {
arr_nama.push( { $(this).attr('id'):$(this).val() } );
});
Upvotes: 0
Reputation: 382170
You seem to want this :
var arr_nama = [];
$("input[name^=ang_nama]").each(function() {
var obj = {};
obj[this.id] = $(this).val();
arr_nama.push(obj);
});
A few observations :
$(this).attr('id')
when you can use this.id
!Another cleaner solution would be
var arr_nama = $("input[name^=ang_nama]").map(function() {
var obj = {};
obj[this.id] = $(this).val();
return obj;
}).get();
Note that this creates an array. If what you wanted is a unique object, use this :
var arr_nama = {};
$("input[name^=ang_nama]").each(function() {
arr_nama[this.id] = $(this).val();
});
Upvotes: 8
Reputation: 388316
Try
var obj = {};
obj[$(this).attr('id')] = $(this).val();
arr_nama.push(obj);
Upvotes: 1