Eric R Eric R - 5 months ago 9
Javascript Question

Remove one object from an array and return the result

I have some objects in an array:

var names = [
{ id:"101", name:"eric" },
{ id:"202", name:"john" },
{ id:"303", name:"zack" },
{ id:"404", name:"ron" }
];


I want to remove one of the objects. I have only one piece data to check the object array against, which is the
id = 202
. Finally, I want to return the adjusted array, like this:

[
{ id:"101", name:"eric" },
{ id:"303", name:"zack" },
{ id:"404", name:"ron" }
];

Answer

With the use of filter:

var res = names.filter(function(obj) {
    return obj.id !== "202";
});

console.log(res);
Comments