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});
}
Community
  • 1
  • 1
benhowdle89
  • 36,900
  • 69
  • 202
  • 331
  • possible duplicate of [Accessing property of object with variable](http://stackoverflow.com/questions/11230063/accessing-property-of-object-with-variable) ... http://stackoverflow.com/questions/4244896/dynamic-object-property-name ... http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-name ... http://stackoverflow.com/questions/11043026/variable-as-the-property-name-in-a-javascript-object-literal ... http://stackoverflow.com/questions/7638659/use-variable-for-property-name-in-javascript-literal These only scratch the surface of the dupes I found in a search. – I Hate Lazy Oct 25 '12 at 19:43
  • This question is not a duplicate of any of the examples you have cited. It additionally asks about pushing an anonymous object into an array. – Aamir Mar 07 '17 at 15:49

1 Answers1

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);
    }
BNL
  • 7,085
  • 4
  • 27
  • 32