How to remove object from array of objects using JavaScript ?
Removing an object from an array of objects in JavaScript refers to the process of eliminating a specific object from the array based on certain conditions, like matching a property value. This task is common in data manipulation, ensuring the array only contains the desired elements.
There are two approaches to solving this problem which are discussed below:
Using array.filter() method with for...of loop
The approach using array.filter() with a for...of loop involves iterating over an array of objects with for...of and applying filter() to exclude specific objects based on a condition. This creates a new array containing only the objects that meet the criteria.
Example: In this example the myFunc() filters arr, deleting the key 'a' from each object. After execution, the modified arr is logged, showing objects without the 'a' property.
let arr = [
{
a: 'Val_1',
b: 'Val_2'
},
{
a: 'Val_3',
b: 'Val_4'
},
{
a: 'Val_1',
b: 'Val_2'
}];
function myFunc() {
arr.filter(obj => {
for (let key in obj) {
if (key === 'a') {
delete obj[key];
}
}
return true;
});
console.log(JSON.stringify(arr));
}
myFunc();
Output
[{"b":"Val_2"},{"b":"Val_4"},{"b":"Val_2"}]
Using Array.reduce() Method
The Array.reduce() method accumulates elements into a new array by iterating through the original array. During this process, it checks each element against a condition, and only adds elements that meet the criteria, effectively removing unwanted objects while constructing the new array.
Example: In this example the myFunc() uses reduce to create newArr from arr, removing the 'a' property from each object. It logs newArr with the 'a' property removed.
let arr = [
{
a: 'Val_1',
b: 'Val_2'
},
{
a: 'Val_3',
b: 'Val_4'
},
{
a: 'Val_1',
b: 'Val_2'
}];
function myFunc() {
let newArr = arr.reduce((acc, obj) => {
let newObj = { ...obj };
delete newObj.a;
acc.push(newObj);
return acc;
}, []);
console.log(JSON.stringify(newArr));
}
myFunc();
Output
[{"b":"Val_2"},{"b":"Val_4"},{"b":"Val_2"}]