JavaScript - How to remove a property from an object

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts:48

JavaScript - How to remove a property from an object

I have an object like this in javascript:

Code: Select all

var obj = {
  prop1: 'val 1',
  prop2: 'val 2',
  prop3: 'val 3'
};
What is the best way to remove the property "prop2" to end up with this new object:

Code: Select all

var obj = {
  prop1: 'val 1',
  prop3: 'val 3'
}

Admin Posts:805
To remove a property from a javascript object, you can use the "delete" instruction.
Example:

Code: Select all

var obj = {
  prop1: 'val 1',
  prop2: 'val 2',
  prop3: 'val 3'
};

delete obj['prop2'];
// OR:
// delete obj.prop2;

console.log(obj);  // {prop1:"val 1", prop3:"val 3"}

Similar Topics