Reputation: 33
I want to be able to remove an object from this object array individually by its key name. So if I wanted to remove item1
I would call a function or something similar and it would remove it completely.
var list = [{item1: 'Foo'}, {item2: 'Bar'}];
removeObjectByKeyName(item1);
I expect the object array after deletion to be [{item2: 'Bar'}]
Any help is appreciated. Thanks!
Upvotes: 0
Views: 42
Reputation: 37755
You can use filter
and hasOwnProperty
var list = [{
item1: 'Foo'
}, {
item2: 'Bar'
}];
var toRemove = 'item1';
var result = list.filter(o => !o.hasOwnProperty(toRemove));
console.log(result);
Upvotes: 0
Reputation: 26844
One option is using filter
to filter the array element with no property name toRemove
var list = [{
item1: 'Foo'
}, {
item2: 'Bar'
}];
var toRemove = 'item1';
var result = list.filter(o => !(toRemove in o));
console.log(result);
With removeObjectByKeyName
function. The first parameter is the key to remove and the second is the array.
let list = [{
item1: 'Foo'
}, {
item2: 'Bar'
}];
let removeObjectByKeyName = (k, a) => a.filter(o => !(k in o));
let result = removeObjectByKeyName('item1', list);
console.log(result);
Upvotes: 2
Reputation: 999
this function will do what you need:
var list = [{item1: 'Foo'}, {item2: 'Bar'}];
function removeObjectByKeyName(list, key) {
return list.filter(item => !Object.keys(item).find(k => k === key) )
}
removeObjectByKeyName(list, 'item1') // [{item2: 'Bar'}]
Upvotes: 0