In this post, I show you how to remove Object from an Array of Objects in JavaScript. This is a common requirement while coding in JavaScript. I hope this post helps you.
Remove Object from an Array of Objects in JavaScript
// using Object Literals
var user1 = {
id : 1,
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29
}
var user2 = {
id : 2,
firstName : 'John',
lastName : 'Cena',
emailId : 'john@gmail.com',
age : 29
}
// we have an array of objects, we want to remove one object using only the id property
var users = [user1, user2];
console.log('Before removing object from an array -> ' + JSON.stringify(users));
// get index of object with id:37
var removeIndex = users.map(function(item) { return item.id; }).indexOf(37);
// remove object
users.splice(removeIndex, 1);
console.log('After removing object from an array -> ' + JSON.stringify(users));
Output:
Before removing object from an array -> [{"id":1,"firstName":"Ramesh","lastName":"Fadatare","emailId":"ramesh@gmail.com","age":29},
{"id":2,"firstName":"John","lastName":"Cena","emailId":"john@gmail.com","age":29}]
After removing object from an array -> [{"id":1,"firstName":"Ramesh","lastName":"Fadatare","emailId":"ramesh@gmail.com","age":29}]
From the above output, the first user object with id = 1 has deleted from Array.
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
Comments
Post a Comment
Leave Comment