How to add or remove properties from a JavaScript object dynamically

by Jagadish Pulakhandam on 9/4/2012 12:46:31 PM
Rated 0 from 0 votes
Brief: Demonstrates on adding and removing properties from a JavaScript object dynamically at run-time.
Posted to: Advanced JavaScript Programming/Development tutorials/videos- Object Oriented Programming
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Attached Source Code/Video demonstrates the following:
  • Creating anonymous objects
  • Adding properties to anonymous objects (during instantiation/creation)
  • Adding properties to objects after instantiation (dynamically at run-time)
  • Removing properties from an object after instantiation (dynamically at run-time)
Source Code:

01.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
03.<html>
04.<head>
05.    <title></title>
06.    <script type="text/javascript">
07.        //DEMO: Deleting/adding properties dynamically
08. 
09.        var oEmp = {
10.            Empno:1001,
11.            Ename:"Jag"
12.        };
13. 
14.        //display properties using a function
15.        function dispEmp(o){
16.            if (o.Sal) { //check if "Sal" property exists
17.                alert(o.Ename + ' earns ' + o.Sal.toString());
18.            }
19.            else {
20.                alert("Sal property does not exist");
21.            }
22.        }
23. 
24.        //add property "Sal" dynamically
25.        oEmp.Sal = 5400;
26.        dispEmp(oEmp); //call unction to display object details
27. 
28.        //remove "Sal" property from the object (dynamically)
29.        delete oEmp.Sal;
30.        dispEmp(oEmp);//call function to display object details
31. 
32. 
33.        //same is possible using constructor functions
34.        var Emp = function () {
35.            this.Empno = 1001;
36.            this.Ename = "Jag";
37.        };
38. 
39.        var oEmp2 = new Emp();
40.        oEmp2.Sal = 5400;
41.        dispEmp(oEmp2); //call function to display object details
42. 
43.        delete oEmp2.Ename;
44.        if(!oEmp2.Ename) alert("Property Ename got removed");
45.    </script>
46.</head>
47.<body>
48. 
49.</body>
50.</html>


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following