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

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

 });

I want field.name should be dynamic.

2
  • "I want field.name should be dynamic." ? Can you elaborate ? Commented May 24, 2016 at 6:00
  • this is showing Uncaught SyntaxError: Unexpected token . (dot) Commented May 24, 2016 at 6:02

2 Answers 2

2

You can use Bracket Notation

var arr=[];
$.each($("#id").serializeArray(), function (i, field) {
   var obj = {};
   obj[field.name] = field.value;
   arr.push(obj );
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.