var arr=[];
$.each($("#id").serializeArray(), function (i, field) {
arr.push({
field.name : field.value
});
});
I want field.name should be dynamic.
var arr=[];
$.each($("#id").serializeArray(), function (i, field) {
arr.push({
field.name : field.value
});
});
I want field.name should be dynamic.
You can use Bracket Notation
var arr=[];
$.each($("#id").serializeArray(), function (i, field) {
var obj = {};
obj[field.name] = field.value;
arr.push(obj );
});
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);