1

Possible Duplicate:
Accessing property of object with variable
How do I add a property to a JavaScript object using a variable as the name?

I'm trying to achieve the following, push an anonymous object into an array, but using the variable 'name' as the Object key. Any ideas how I could achieve this?

var json = $('form[name="edit-form"]').serializeArray();
var data = {};
data.user = [];
var l = json.length;
for(var i = 0; i < l; i++){
  var name = json[i].name;
  var value = json[i].value;
  data.user.push({[name]: value});
}
2

1 Answer 1

4

Something like this? Assuming what you are looking for is an object with a property taken from the name variable containing the value.

    var json = $('form[name="edit-form"]').serializeArray();
    var data = {};
    data.user = [];
    var l = json.length;
    for(var i = 0; i < l; i++){
        var name = json[i].name;
        var value = json[i].value;
        var tempObj = {};
        tempObj[name] = value;
        data.user.push(tempObj);
    }
Sign up to request clarification or add additional context in comments.

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.