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?
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();
});
input. For some elements it's not exactly the same behavior, that's why I'm reluctant to change it.Try this, add curly braces while pushing
$("input[name^=ang_nama]").each(function() {
arr_nama.push( { $(this).attr('id'):$(this).val() } );
});