简体   繁体   English

如何从对象数组中删除虚假值

[英]How to remove falsy values from array of objects

I have an array of objects like so,我有一个像这样的对象数组,

const arr = [
 {                                       
  'first name': 'john',               
  'last name': 'doe',            
  age: '22',                            
  'matriculation number': '12349',      
  dob: '12/08/1997'                     
},                                      
{                                       
  'first name': 'Jane',               
  'last name': 'Doe',            
  age: '21',                            
  'matriculation number': '12345',      
  dob: '31/08/1999'                     
},                                      
{                                       
  'first name': '',                     
  'last name': undefined,               
  age: undefined,                       
  'matriculation number': undefined,    
  dob: undefined                        
}                                       
]

I want to remove the last object from the array since it has falsy values, I tried to achieve this by writing a simple function like so我想从数组中删除最后一个 object 因为它具有虚假值,我试图通过编写一个简单的 function 来实现这一点

function removeFalsy(obj) {
  for (let i in obj) {
    if (!obj[i]) {
      delete obj[i]
    }
  }
  return obj
}

That didn't fix the issue, I also tried to use这并没有解决问题,我也尝试使用

arr.map((a) => Object.keys(a).filter((b) => Boolean(b)))

but that just returned the keys in the object, how can I achieve this, please?但这只是返回了 object 中的密钥,请问我该如何实现?

Thanks谢谢

Assuming that you want to remove all object with falsey values, you can use Array.prototype.filter on the input array, as well as Array.prototype.every to check entry values for being falsey假设您要删除所有具有虚假值的 object,您可以在输入数组上使用Array.prototype.filter以及Array.prototype.every来检查条目值是否为虚假

 const arr = [{ 'first name': 'john', 'last name': 'doe', age: '22', 'matriculation number': '12349', dob: '12/08/1997' }, { 'first name': 'Jane', 'last name': 'Doe', age: '21', 'matriculation number': '12345', dob: '31/08/1999' }, { 'first name': '', 'last name': undefined, age: undefined, 'matriculation number': undefined, dob: undefined } ]; const result = arr.filter((el) => Object.values(el).every(Boolean)); console.log(result)

try this尝试这个

 const noFalsies = arr.filter( ( element) => {
        const props = Object.values(element)
        return ! props.some( (aProp) => !aProp)
      }
      )

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

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