Delete object by value javascript

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"}

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.

Can we delete object in JavaScript?

Remove Property from an Object The delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.

How do you nullify an object in JavaScript?

In order to set object values to null, you need to get all the keys from the object and need to set null. You can use for loop or forEach() loop. node fileName. js.

How do you remove an element from an object?

Answer: Use the delete Operator You can use the delete operator to completely remove the properties from the JavaScript object. Deleting is the only way to actually remove a property from an object.

How do you delete an object from an array?

There are different methods and techniques you can use to remove elements from JavaScript arrays:.
pop - Removes from the End of an Array..
shift - Removes from the beginning of an Array..
splice - removes from a specific Array index..
filter - allows you to programatically remove elements from an Array..