Suppose I have a javascript Object
var MyObject= { "Name": "Value1", "Email": "test@gmail.com" };
And now I want to add a new property or remove a property from the above object, how can I achieve it in javascript?
you can delete object using delete
Example:
delete MyObject.Name;
// or,
delete MyObject['Name'];
// or,
var prop = "Name";
delete MyObject[prop];
Another way to delete an object is to undefined it
obj.field = undefined;
//use this approach when you care about performance
Adding a property to object
Adding a proerty is easy, if you know the basics of Javascript Objects
MyObject.NewProperty = "NewValue";
//you can get the value using
alert(MyObject.NewProperty);
You can remove property from JS object as below
var myObject = {"Hello": "SomeText", "Hello2": "New hello", "Hello3": "Hello from 3"};
delete myObject.Hello3;
console.log(myObject.Hello3); // logs: undefined
Add Property in JS objects
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
data["PropertyD"] = 4;
console.log(data.PropertyD); //output: 4
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly