Reputation: 50732
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
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