How to remove object from array of objects using JavaScript ?

Given a JavaScript array containing objects, the task is to delete certain objects from an array of objects. and return the newly formed array after deleting that element.

There are two approaches to solving this problem which are discussed below: 

Table of Content

  • Using array.forEach() method
  • Using array.map() method
  • Using array.filter() method with for…of loop

Using array.forEach() method

  • Use array.forEach() method to traverse every object of the array.
  • For each object, use the delete obj.property to delete the certain object element from an array of objects.

Example: This example implements the above approach. 

Javascript
let arr = [{
    a: 'Val_1',
    b: 'Val_2'
}, {
    a: 'Val_3',
    b: 'Val_4'
}, {
    a: 'Val_1',
    b: 'Val_2'
}];

function myFunc() {
    arr.forEach(function (obj) {
        delete obj.a
    });

    console.log(JSON.stringify(arr));
}

myFunc();

Output
[{"b":"Val_2"},{"b":"Val_4"},{"b":"Val_2"}]

Using array.map() method

  • Use array.map() method to traverse every object of the array.
  • For each object use the delete obj.property to delete the certain object from an array of objects.

Example: This example implements the above approach. 

Javascript
let arr = [{
    a: 'Val_1',
    b: 'Val_2'
}, {
    a: 'Val_3',
    b: 'Val_4'
}, {
    a: 'Val_1',
    b: 'Val_2'
}];

function myFunc() {
    arr.map(function (obj) {
        delete obj.a;
        return obj;
    });

    console.log(JSON.stringify(arr));
}

myFunc();

Output
[{"b":"Val_2"},{"b":"Val_4"},{"b":"Val_2"}]

Using array.filter() method with for…of loop

Use the array.filter() method to traverse every object of the array. For each object, use a for…of loop to delete the specific property. Finally, return the modified array.

Example:

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


Contact Us