Thursday, June 26, 2008

JavaScript | Print all properties of Object

To Print all properties of an object in JavaScript, use for-in as follows:


<script language="Javascript">
var obj = new Object(); //Create new object
obj["firstName"]="Davendra"; //Assign property firstName with value Davendra
obj["lastName"]="Upreti"; //Assign property lastName with value Upreti
var str=""; //variable which will hold property values
for(prop in obj)
{
str+=prop + " value :"+ obj[prop]+"\n"; //Concate prop and its value from object
}
alert(str); //Show all properties and its value
</script>