How to remove a property from a JavaScript object?

· · 2529 views

Here I have a object:

let myObject = {
  "item1": "value",
  "item2": "value",
  "item3": "value"
};

What is the best way to remove the property from this myObject variable?

0
2 Answers

You can use delete keyword to remove properties from objects.

if(myObject.hasOwnProperty('item1')) {
	delete myObject.item1;
}

Note that, To remove an element from an array, use Array.splice or Array.pop. For example:

arr // [0, 1, 2, 3, 4]
arr.splice(3,1); // 3
arr // [0, 1, 2, 4]

The delete keyword in JavaScript has a different function to that of the keyword in C and C++: it does not directly free memory. Instead, its only purpose is to delete properties from objects.

For arrays, removing a property corresponding to an index, creates a sparse array (ie. an array with a "hole" in it). Most browsers represent these missing array indices as "empty".

var array = [0, 1, 2, 3]
delete array[2] // [0, 1, empty, 3]

Different built-in functions in JavaScript handle sparse arrays differently.

  • for...in will skip the empty index completely.
  • A traditional for loop will return undefined for the value at the index.
  • Any method using Symbol.iterator will return undefined for the value at the index.
  • forEach, map and reduce will simply skip the missing index.

So, the delete keyword should not be used to removing elements from an array. Arrays have a dedicated methods for removing elements and reallocating memory: Array.splice() and Array.pop.

Array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

let a = [0,1,2,3,4]
a.splice(2,2) // returns the removed elements [2,3]
// ...and `a` is now [0,1,4]

Array.slice([begin[, end]])

let a = [0,1,2,3,4]
let slices = [
    a.slice(0,2),
    a.slice(2,2),
    a.slice(2,3),
    a.slice(2,5) ]

//   a           [0,1,2,3,4]
//   slices[0]   [0 1]- - -   
//   slices[1]    - - - - -
//   slices[2]    - -[3]- -
//   slices[3]    - -[2 4 5]

Array.pop

Array.pop removes the last element from an array, and returns that element. This operation changes the length of the array.

0

Objects in JavaScript can be thought of as maps between keys and values. The delete operator is used to remove these keys.

var obj = {
  myProperty: 1    
}
console.log(obj.hasOwnProperty('myProperty')) // true
delete obj.myProperty
console.log(obj.hasOwnProperty('myProperty')) // false

Or, you can use object destructuring, an ECMAScript 6 feature, it's as simple as:

let myObject = {
  "item1": "value",
  "item2": "value",
  "item3": "value"
};
({ item1, ...myObject } = myObject);
console.log(myObject);
0

Please login or create new account to participate in this conversation.