3

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?

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

"don't use $(this).attr('id') when you can use this.id " same for value :)
@roasted yes, but only because it's an input. For some elements it's not exactly the same behavior, that's why I'm reluctant to change it.
1

Try

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

Comments

0

Try this, add curly braces while pushing

$("input[name^=ang_nama]").each(function() {
     arr_nama.push( { $(this).attr('id'):$(this).val() } );
});

1 Comment

No, you can't do this in JavaScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.