Here is a suggestion for what you actually asked:
http://jsfiddle.net/mplungjan/b5yRw/
Of course, he will work with the form.
var GenderValue = "F";
var DateOfBirthValue;
var AddressValue = "some street";
function addItem(obj,varName) {
obj[varName] = window.hasOwnProperty(varName+"Value")?window[varName+"Value"]||"not set":"not declared";
}
function addItemLoop(obj) {
for (var o in obj) {
if (typeof obj[o] === 'object') {
addItemLoop(obj[o]);
}
else {
addItem(obj, o);
}
}
}
AddPatient = {
Gender : " ",
DateOfBirth: " ",
ResidentialAddress : {
Address:" ",
City: " "
}
}
addItemLoop(AddPatient);
document.write("<br/>Gender (F):"+AddPatient.Gender);
document.write("<br/>DOB (not set):"+AddPatient.DateOfBirth);
document.write("<br/>ResidentialAddress Address (some street):"+AddPatient.ResidentialAddress.Address);
document.write("<br/>ResidentialAddress City (not declared):"+AddPatient.ResidentialAddress.City);
Previous answer
Not better, but shorter using the ternary operator
AddPatient.Gender = (GenderValue === undefined)? " ":GenderValue;
or shortcut
AddPatient.Gender = GenderValue || " ";
Note. In the shortcut you will get a space if the value is 0
, GenderValue .
- var GenderValue;
:
var b="hello", c;
var a = {}
a.x = b||"no b"
a.y = (c===undefined)? "no c here":c
a.z = c || "no c here either"
alert(a.x)
alert(a.y)
alert(a.z)