creating json object with variables

后端 未结 5 1260
清歌不尽
清歌不尽 2020-12-25 13:05

I am trying to create a json object from variables that I am getting in a form.

var firstName = $(\'#firstName\').val();
var lastName  = $(\'#lastName\').va         


        
相关标签:
5条回答
  • 2020-12-25 13:21

    It's called on Object Literal

    I'm not sure what you want your structure to be, but according to what you have above, where you put the values in variables try this.

    var formObject =  {"formObject": [
                    {"firstName": firstName, "lastName": lastName},
                    {"phoneNumber": phone},
                    {"address": address},
                    ]}
    

    Although this seems to make more sense (Why do you have an array in the above literal?):

    var formObject = {
       firstName: firstName
       ...
    }
    
    0 讨论(0)
  • 2020-12-25 13:39

    Try this to see how you can create a object from strings.

    var firstName = "xx";
    var lastName  = "xy";
    var phone     = "xz";
    var adress    = "x1";
    var obj = {"firstName":firstName, "lastName":lastName, "phone":phone, "address":adress};
    console.log(obj);
    
    0 讨论(0)
  • 2020-12-25 13:41
    var formValues = {
        firstName: $('#firstName').val(),
        lastName: $('#lastName').val(),
        phone: $('#phoneNumber').val(),
        address: $('#address').val()
    };
    

    Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.

    0 讨论(0)
  • 2020-12-25 13:43

    You're referencing a DOM element when doing something like $('#lastName'). That's an element with id attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject is in the same scope as the variable declarations) -

    var formObject = {
        formObject: [
            {
                firstName:firstName,  // no need to quote variable names
                lastName:lastName
            },
            {
                phoneNumber:phoneNumber,
                address:address
            }
        ]
    };
    

    This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.

    0 讨论(0)
  • 2020-12-25 13:46

    if you need double quoted JSON use JSON.stringify( object)

    var $items = $('#firstName, #lastName,#phoneNumber,#address ')
    var obj = {}
    $items.each(function() {
        obj[this.id] = $(this).val();
    })
    
    var json= JSON.stringify( obj);
    

    DEMO: http://jsfiddle.net/vANKa/1

    0 讨论(0)
提交回复
热议问题