I have an JavaScript object like this:
id="1";
name = "serdar";
and I have an Array which contains many objects of above. How can I remove an object from that array such as like that:
obj[1].remove();
I have an JavaScript object like this:
id="1";
name = "serdar";
and I have an Array which contains many objects of above. How can I remove an object from that array such as like that:
obj[1].remove();
If you have access to ES2015 functions, and you're looking for a more functional approach I'd go with something like:
const people = [
{ id: 1, name: 'serdar' },
{ id: 5, name: 'alex' },
{ id: 300, name: 'brittany' }
];
const idToRemove = 5;
const filteredPeople = people.filter((item) => item.id !== idToRemove);
// [
// { id: 1, name: 'serdar' },
// { id: 300, name: 'brittany' }
// [
Watch out though, filter() is non-mutating, so you'll get a new array back.
Cleanest and fastest way (ES6)
const apps = [
{id:1, name:'Jon'},
{id:2, name:'Dave'},
{id:3, name:'Joe'}
]
//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}
apps.splice(apps.findIndex(a => a.id === itemToBeRemoved.id) , 1)
//print result
console.log(apps)
Update: if any chance item doesn't exist in the look up array please use below solution, updated based on MaxZoom's comment
const apps = [
{id:1, name:'Jon'},
{id:3, name:'Joe'}
]
//remove item with id=2
const itemToBeRemoved = {id:2, name:'Dave'}
const findIndex = apps.findIndex(a => a.id === itemToBeRemoved.id)
findIndex !== -1 && apps.splice(findIndex , 1)
//print result
console.log(apps)
we have an array of objects, we want to remove one object using only the id property
var apps = [
{id:34,name:'My App',another:'thing'},
{id:37,name:'My New App',another:'things'
}];
get the index of the object with id:37
var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);
// remove object
apps.splice(removeIndex, 1);