0

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!

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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'}]

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.