0
var arr=[];
$.each($("#id").serializeArray(), function (i, field) {

    arr.push({
        field.name : field.value
    });

 });

I want field.name should be dynamic.

ML680
  • 99
  • 1
  • 1
  • 10

2 Answers2

2

You can use Bracket Notation

var arr=[];
$.each($("#id").serializeArray(), function (i, field) {
   var obj = {};
   obj[field.name] = field.value;
   arr.push(obj );
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

showing Uncaught SyntaxError: Unexpected token .

It is because, LHS contains a . in

arr.push({
    field.name : field.value //field.name on LHS contains a dot, which is not correct syntax
});

As per spec (section 6 Objects)

An object structure is represented as a pair of curly bracket tokens surrounding zero or more name/value pairs. A name is a string. A single colon token follows each name, separating the name from the value. A single comma token separates a value from a following name.

If your property name is dynamic, then use bracket notation as @Satpal has shown above.

var obj = {};
obj[field.name] = field.value; 
arr.push(obj);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94