How to remove Objects from Associative Array in JavaScript ?
Last Updated :
13 Jul, 2023
In this article, we are going to learn about removing Objects from Associative Array in Javascript, In JavaScript, you can remove objects from an associative array (also known as an object) using the following methods.
Approaches:
Declare an associative array containing key-value pair objects. Then use the delete keyword to delete the array objects from an associative array.
Example 1: This example uses the delete keyword to remove the objects from the associative array.
javascript
function deleteObjects() {
let arr = new Object();
arr[ 'key' ] = 'Value' ;
arr[ 'geeks' ] = 'GeeksforGeeks' ;
arr[ 'name' ] = 'Rajnish' ;
console.log(arr[ 'name' ]);
delete arr[ 'name' ];
console.log(arr[ 'name' ]);
}
deleteObjects();
|
Example 2: This example uses the delete keyword to remove the objects from the associative array.
javascript
function deleteObjects() {
let arr = new Object();
arr[ 'key' ] = 'Value' ;
arr[ 'geeks' ] = 'GeeksforGeeks' ;
arr[ 'name' ] = 'Rajnish' ;
console.log(arr[ 'geeks' ]);
delete arr.geeks;
console.log(arr[ 'geeks' ]);
}
deleteObjects();
|
Output
GeeksforGeeks
undefined
The JavaScript Array filter() Method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method.
Syntax:
array.filter(callback(element, index, arr), thisValue)
Example:
Javascript
function deleteObjects() {
let arr = new Object();
arr[ 'key' ] = 'Value' ;
arr[ 'geeks' ] = 'GeeksforGeeks' ;
arr[ 'name' ] = 'JavaScript' ;
console.log(arr[ 'name' ]);
const updatedArray = Object.fromEntries(
Object.entries(arr).filter(([key]) => key !== 'name' )
);
return updatedArray;
}
console.log(deleteObjects());
|
Output
JavaScript
{ key: 'Value', geeks: 'GeeksforGeeks' }
Lodash is a JavaScript library that works on top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.omit() method is used to return a copy of the object that is composed of the own and inherited enumerable property paths of the given object that are not omitted. It is the opposite of the _.pick() method.
Syntax:
_.omit( object, paths )
Example:
Javascript
function deleteObjects() {
const _ = require( "lodash" );
let arr = new Object();
arr[ 'key' ] = 'Value' ;
arr[ 'geeks' ] = 'GeeksforGeeks' ;
arr[ 'name' ] = 'JavaScript' ;
console.log(arr[ 'key' ]);
const updatedArray = _.omit(arr, 'key' );
return updatedArray;
}
console.log(deleteObjects());
|
Output:
Value
{ geeks: 'GeeksforGeeks', name: 'JavaScript' }
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...