0

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 ?

2 Answers 2

4

You can try

UserDataObj[key] = value;
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.