user1009073 user1009073 - 3 months ago 9
Javascript Question

Javascript - creating new object, but not passing any parameters

New to Javascript. Trying to create a datatype (assuming OBJECT is what I am wanting here) definition that can be used between various functions. The definition, as of now, is only variables (no functions etc). The issue I am having is that I want to initially create it, and then later set the properties...

What I would LIKE to do... is have a definition.

// Object Definition
function resultObj = {
isValid: true,
nn_name: '',
account_name: '',
translated_name: '',
address1: '',
city: '',
state: '',
zip: '',
country: '',
formattedAddress : '',
auth_string: '',
error_text: '',
error_body: '',
error_type: ''
};


At some point, I will create an occurrence of that definition.

myData = new resultObj;
... do some processing here...
... set a FEW of the variables
myData.zip = '12345';


How can I create this so that I don't have to pass in all the values (or empty parameters) at creation time?

Answer

How about you create your original default/initial object and then whenever you have to create an another new/independent object with the very same initial properties, you just copy that old object in new one?

var myData = Object.assign({}, resultObj); 

You can use Object.assign to create an exact copy.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

var resultObj = {
    isValid: true,
    nn_name: '',
    account_name: '',
    translated_name: '',
    address1: '',
    city: '',
    state: '',
    zip: '',
    country: '',
    formattedAddress : '',
    auth_string: '',
    error_text: '',
    error_body: '',
    error_type: ''    
};

var myData = Object.assign({}, resultObj);
document.write(JSON.stringify(myData));  

Also see: How do I correctly clone a JavaScript object?