Wildan Muhlis
Wildan Muhlis

Reputation: 1603

Javascript object with .push() method

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

Answers (3)

amrinder007
amrinder007

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

Denys Séguret
Denys Séguret

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 :

  • don't use $(this).attr('id') when you can use this.id !
  • you have to initialize the array before you push to it
  • you can't directly create an object literal with a dynamic property name, you must create the object first

Another cleaner solution would be

var arr_nama = $("input[name^=ang_nama]").map(function() {
   var obj = {};
   obj[this.id] = $(this).val();
   return obj;
}).get();

Demonstration

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

Demonstration

Upvotes: 8

Arun P Johny
Arun P Johny

Reputation: 388316

Try

var obj = {};
obj[$(this).attr('id')] = $(this).val();
arr_nama.push(obj);

Upvotes: 1

Related Questions