← coderrocketfuel.com

3 Different Ways To Remove A Property From A Node.js Object

In Node.js, there are a couple of different ways to remove a property from an object.

In this article, we'll show you how each one works.

Let's get started!

Table Of Contents

Use The Delete Method

From a semantic standpoint, the delete method is the easiest way to remove a property from an object.

Given an object:

const names = {
  father: "Johnny",
  brother: "Billy",
  sister: "Sandy"
}

We can remove the father property and its value from the object with either of the two ways below:

delete names.father
// { brother: "Billy", sister: "Sandy" }

delete names["father"]
// { brother: "Billy", sister: "Sandy" }

Although this method is easy to use, it will get very slow when working with a large object with lots of properties.

So, we will go through a couple more methods you can use that may be faster or suit your needs better in different situations.

Set Property Value To Undefined, Null, Or False

This method will work best when you are working with large objects and need your code to be more optimized for speed.

Keep in mind that the property isn't completely removed with this method, but its value is wiped clean. So the property will still be there if you iterate over the object later on.

Given the same object as before:

const names = {
  father: "Johnny",
  brother: "Billy",
  sister: "Sandy"
}

We can set the value of the father property to undefined, null, or false with the code below:

names.father = undefined
// { brother: "Billy", sister: "Sandy", father: undefined }

names.father = null
// { brother: "Billy", sister: "Sandy", father: null }

names.father = false
// { brother: "Billy", sister: "Sandy", father: false }

Only use this method if you have a good reason to do so. The delete method is still really fast and good enough for most use cases.

Use Object.keys() To Remove Without Mutation

If the mutation of your object is a concern, you can use the Object.keys() method to create a completely new object by copying all the properties and values over to a new object. But exclude the one you want to remove.

Given the same object:

const names = {
  father: "Johnny",
  brother: "Billy",
  sister: "Sandy"
}

Here's how it's done:

const newNames = Object.keys(names).reduce((object, key) => {
  if (key !== "father") {
    object[key] = names[key]
  }
  return object
}, {})

// { brother: "Billy", sister: "Sandy" }

The Object.keys(names) creates an array of all the properties in the object: ["father", "brother", "sister"].

Then we use the reduce() method to execute code for each value in the new array created by Object.keys().

For each item in the reduce() method, we check whether or not the value is "father". And if the value is not equal to "father", we add it to our new object.

In the end, we are left with a new object called newNames that has the "father" property and it's value excluded.

Thanks for reading and happy coding!