how to add-remove property in Javascript Object?


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?


Asked by:- pika
2
: 1753 At:- 6/20/2017 3:17:39 PM
javascript add-remove javascript-objects







2 Answers
profileImage Answered by:- Vipin

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);

1
At:- 6/21/2017 8:21:04 AM Updated at:- 12/9/2022 7:30:27 AM


profileImage Answered by:- Vinnu

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.

0
At:- 12/9/2022 3:58:57 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use