Different ways to remove the key from the javaScript object

Objects in JavaScript can be thought of as maps between keys and values. We can remove these keys, more commonly known as object properties. In this tutorial, we will learn different ways to delete the key/property of the JavaScript object.

Let’s declare an object in javascript with inline initialization of keys and values. We will use this throughout this post

let carObj = {
    "name": "alto",
    "age": "5",
    "type": "car",
    "location": "India"
}

1. delete

The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned.

delete object.property

OR
delete object['property']
delete carObj.location;
OR
delete carObj['location'];

console.log(carObj.location); // undefined

2. Reflect.deleteProperty

The static Reflect.deleteProperty() method allows to delete properties. It is like the delete operator as a function.

Reflect.deleteProperty(target, propertyKey)
Reflect.deleteProperty(carObj, 'location');
console.log(carObj.location); // undefined

3. Spread syntax (…)

Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

const { location, ...carObj} = carObj;
OR // If we have dynamic key
let key = 'location'
const { [key]:foo, ...carObj} = carObj;
console.log(carObj.location); // undefined

In this new carObj created without a location key.

4. Using lodash libarary

1. _.omit

The opposite of _.pick; this method creates an object composed of the own and inherited enumerable property paths of object that are not omitted.

In short, it returns a new copy of the object after removing the given keys.

_.omit(carObj, ['locaton']);
console.log(carObj.location); // undefined

2. _.pick

Creates an object composed of the picked object properties.

In short, It returns a new copy of the object with given keys.

_.pick(carObj, ['name', 'age','type']);
console.log(carObj.location); // undefined

Leave a Reply