JavaScript: Remove a Property from an Object

Introduction

An object in JavaScript is a collection of key-value pairs. One of these key-value pairs is called an object property. Both keys and values of properties can be of any data type - Number, String, Array, Object, etc.

For example:

const dog = {
    name: "Sandy",
    age: 3,
    emoji: "🐶"
}

Here, name: "Sandy", age: 3, and emoji: "🐶" are the properties of a dog object.

In this article, we will look at a few ways to remove a property from an Object and compare them to understand which method is appropriate in a given context.

Remove a Property From an Object

The delete Operator

The semantically correct way to delete a property from an object is the delete operator. Let's see it in action:

const student = {
    name: "Jane",
    age: 16,
    score: {
        maths: 95,
        science: 90
    }
}

// Deleting a property from an object
delete student.age
delete student["score"]

console.log(student) // {name: "Jane"}

In the example above, the delete operator is used to remove the name and score properties from the student object.

Trying to access any of the deleted properties will return undefined:

console.log(student.age) // undefined

Also, the delete operator returns a boolean value which signifies if the deletion was successful:

if (delete student.age) {
    console.log("Removed 'age' property from student");
} else {
    console.log("Failed to remove 'age' property, perhaps it doesn't exist?");
}

If we run this code, since the property is already deleted, we're greeted with:

Failed to remove 'age' property, perhaps it doesn't exist?

New Object Without the Property

If we don't want to modify an object in-place, but also want a version of it without a specific property, we can just generate another object with all the same properties but the one.

In cases when we know the name of the property we want to remove, we can just use object destructuring to unpack the object into 2 parts:

  1. The property we want to remove
  2. An object that represents the rest of the object
const car = {
    brand: "Ford",
    color: "blue",
    yearOfManufacturing: 2019
}

const {yearOfManufacturing, ...rest} = car;

console.log(rest); // {brand: "Ford", color: "blue"}
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

However, if we don't know the exact name of the property we want to remove, we'll need to make a filter that will check if a property meets the deletion criteria.

For example, let's remove all properties that have a numeric value:

const developer = {
  name : "Fred",
  dailyCoffeIntake : 2,
  favoriteLanguage : "Haskell",
  age : 27
};

const keysToKeep = Object.keys(developer).filter(
  (key)=> {
    return !Number.isInteger(developer[key])
});

const newDeveloper = {};
keysToKeep.forEach((key)=>{
  newDeveloper[key] = developer[key]
});

console.log(newDeveloper); // {name: "Fred", favoriteLanguage: "Haskell"}

The reduce() Function

Alternatively we can use the reduce() method, which is a built-in array method which takes a collection and a reduction function as an argument.

The function then iterates through all elements in the collection and modifies the accumulator (which you can think of as a temporary result for every step) and returns it. Let's see this method in action:

const dog = {
    name: "Sandy",
    age: 3,
    emoji: "🐶"
}

const newDog = Object.keys(dog).reduce((accumulator, key) => {
    // Copy all except emoji
    if(key !== "emoji"){
        accumulator[key] = dog[key]
    }
    return accumulator
}, {})

console.log(newDog) // {name: "Sandy", age: 3}

Conclusion

In this article, we have seen how to remove a property from an object in a few ways. We have seen that using delete will mutate the object. So, we have discussed a couple ways - the ...rest syntax and reduce() method, to remove a property from an object without mutating it.

Last Updated: August 25th, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Abhilash KakumanuAuthor

Hey, I am a full-stack web developer located in India. I am a curious person who is always trying to wrap my head around new technologies. In my free time, I read novels and play with my dog!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms