简体   繁体   English

如何通过对象键名从对象数组中删除对象?

[英]How to remove object from object array by object key name?

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. 因此,如果我想删除item1我会调用一个函数或类似的东西,它将完全删除它。

var list = [{item1: 'Foo'}, {item2: 'Bar'}];

removeObjectByKeyName(item1);

I expect the object array after deletion to be [{item2: 'Bar'}] 我希望删除后的对象数组为[{item2: 'Bar'}]

Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

One option is using filter to filter the array element with no property name toRemove 一种选择是使用filter过滤没有属性名称的数组元素以toRemove

 var list = [{ item1: 'Foo' }, { item2: 'Bar' }]; var toRemove = 'item1'; var result = list.filter(o => !(toRemove in o)); console.log(result); 


With removeObjectByKeyName function. 具有removeObjectByKeyName函数。 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); 

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

You can use filter and hasOwnProperty 您可以使用filterhasOwnProperty

 var list = [{ item1: 'Foo' }, { item2: 'Bar' }]; var toRemove = 'item1'; var result = list.filter(o => !o.hasOwnProperty(toRemove)); console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM