Remove | Delete Property of an Object

Last Updated On Saturday 30th Oct 2021

remove key from object javascript

JavaScript remove property from object.

delete operator

The JavaScript delete operator removes a property from an object.

Syntax

	delete object.property
delete object['property']
	
	const myObj = {
    'first': 'one',
    'second': 'two',
    'third': 'three'
}

delete myObj.second;
or
delete myobj['second'];

console.log(myObj)

// { first: 'one', third: 'three' }
	

Reduce Method

The reduce() method executes a user-supplied reducer callback function on each element of the array, passing in the return value from the calculation on the preceding element.

Syntax

	// Arrow function
reduce((previousValue, currentValue) => { ... } )
	
	const myObj = {
    'first': 'one',
    'second': 'two',
    'third': 'three'
}

const removeThird = Object.keys(myObj).reduce((acc, key) => {
    if (key !== 'third') {
        acc[key] = myObj[key]
    }
    return acc
}, {})

console.log(removeThird)
// { first: 'one', second: 'two' }
	

javascript object remove key

Omit Method Lodash

Omit function provided by the Lodash library which can be used to delete property from an object in javascript.

	import { omit } from 'lodash'

const myObj = {
    'first': 'one',
    'second': 'two',
    'third': 'three'
}

omit(myObj, [ 'first', 'third' ])

console.log(myObj)

// { 'second': 'two' }
	

Pick Method Lodash

	import { pick } from 'lodash'

const myObj = {
    'first': 'one',
    'second': 'two',
    'third': 'three'
}

pick(myObj, [ 'second' ])

console.log(myObj)

// { 'second': 'two' }
	

javascript remove key from object

Filter Method

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Syntax

	// Arrow function
filter((element) => { ... } )
filter((element, index) => { ... } )
filter((element, index, array) => { ... } )
	

Use the filter to remove the property from an object.

	const myObj = {
    'first': 'one',
    'second': 'two',
    'third': 'three'
}

let filtered = {}
Object.keys(myObj).filter(prop => {
    if (prop !== 'third') {
        filtered[prop] = myObj[prop]
    }
})

console.log(filtered)
	

Object destructuring with rest syntax

It is immutable since it doesn’t modify the original object.

Destructure the object to the property you want to remove, and the remaining properties collect into a rest object.Dmitri Pavlutin Explained Very Well in this WonderFul Article.

remove property from object javascript

	const myObj = {
    'first': 'one',
    'second': 'two',
    'third': 'three'
}

const { third, ...restOnes } = myObj;

console.log(restOnes);
console.log(myObj);
	

References