copenndthagen
copenndthagen

Reputation: 50732

Setting JavaScript Object literal value

I have a JS object as follows;

var UserDataObj = {
    name: "John",
    email: "[email protected]",
    phone: "9999999999",
    desc: "some description"
}

Now this is a global var.

Inside one of my function to save form data,

I have

$(".formFieldUserData").each(function(){
    var key = $(this).attr("name");
    var value = $(this).val();
    UserDataObj.key = value;
})

Now I want to update the default values in UserDataObj with the values entered by the user. I am not sure if the line UserDataObj.key = value; is correct

I need the key to correspond to the object property..I have the same name...

How do I fix this ?

Upvotes: 0

Views: 415

Answers (2)

darshanags
darshanags

Reputation: 2519

Original object:

var UserDataObj = {
    name: "John",
    email: "[email protected]",
    phone: "9999999999",
    desc: "some description"
}

Setup and populate new object:

var userData = {};

$(".formFieldUserData").each(function(){
    var $this = $(this);
    userData[$this.attr("name")] = $this.val();
});

Merge new data into the data we already have:

$.extend(UserDataObj, userData);

Note: $.extend will modify the UserDataObj to contain both old and new data.

Upvotes: 0

Fopfong
Fopfong

Reputation: 299

You can try

UserDataObj[key] = value;

Upvotes: 4

Related Questions