Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding members to an existing object

Tags:

javascript

Suppose we have the following object:

var obj = {     fn1: function() {     } } 

how can I dynamically add another member to it, say

fn2: function() {} 
like image 662
Jon Doe Avatar asked Jan 05 '11 05:01

Jon Doe


People also ask

What is ADD-member in PowerShell?

The Add-Member cmdlet lets you add members (properties and methods) to an instance of a PowerShell object. For instance, you can add a NoteProperty member that contains a description of the object or a ScriptMethod member that runs a script to change the object.

How do you add members to an array?

If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().

How do you append an object in PowerShell?

Use += to Add Objects to an Array of Objects in PowerShell The Plus Equals += is used to add items to an array. Every time you use it, it duplicates and creates a new array. You can use the += to add objects to an array of objects in PowerShell.


1 Answers

As others have pointed out:

obj.fn2 = function(){ ... }; 

Note that if "fn2" is not a valid identifier, you must instead use the 'array' notation for the object:

obj["fn2"] = function(){ ... }; obj["!! crazy-names#allowed?!"] = function(){ ... }; 

This is also how you would do it if you had the name of the property stored in a variable:

var propName = "fn2"; obj[propName] = function(){ ... }; 

If you want to test if a property exists for an object, you can use the in operator:

if ("fn2" in obj){ ... } 

If you want to remove a property from an object, use the delete keyword:

var o = { a:42 }; console.log( "a" in o ); // true delete o.a;              // Or delete o["a"] console.log( "a" in o ); // false 

To iterate over all properties in an object, use the in operator in a for loop. Be sure to var the variable so that it isn't global:

var o = { a:42, b:17 }; var allPropertyNames  = []; var allPropertyValues = []; for (var propName in o){   // If you don't do this test, propName might be a property inherited   // by this object, and not a property on the object itself.   if (o.hasOwnProperty(propName)){     allPropertyNames.push(propName);     allPropertyValues.push(o[propName]);   } } console.log( allPropertyNames );  // [ "a", "z" ] console.log( allPropertyValues ); // [ 42, 17 ] 
like image 52
Phrogz Avatar answered Oct 16 '22 17:10

Phrogz