简体   繁体   English

从对象数组中删除空对象

[英]Remove empty object from array of objects

I have an array of objects and a delete function that pass the index as a parameter but fails to remove the empty object.我有一个对象数组和一个删除函数,该函数将索引作为参数传递但未能删除空对象。 Objects containing properties can be removed.可以删除包含属性的对象。 Does anyone know how to fix it?有谁知道如何修理它? The example code is shown below.示例代码如下所示。

let array = [
{
  id: '1',
  name: 'sam',
  dateOfBirth: '1998-01-01'
},
{
  id: '2',
  name: 'chris',
  dateOfBirth: '1970-01-01'
},
{
  id: '3',
  name: 'daisy',
  dateOfBirth: '2000-01-01'
},
{}
]

// Objects contain properties can be removed but empty object can not be removed.
const deleteItem = (index) => {
  return array.splice(index, 1);
};

Use Array.filter to filter out the items which have no properties使用Array.filter过滤掉没有属性的项目

 let array = [ {id:"1",name:"sam",dateOfBirth:"1998-01-01"}, {id:"2",name:"chris",dateOfBirth:"1970-01-01"}, {id:"3",name:"daisy",dateOfBirth:"2000-01-01"}, {} ] const filtered = array.filter(e => Object.keys(e).length) console.log(filtered)

The above works since Object.keys will return an array of the properties of the object.上述工作是因为Object.keys将返回对象属性的数组。 Getting its length property will get the number of items in the array.获取其length属性将获取数组中的项目数。 If the length property is 0 , it is coerced to false (see: Falsy values ).如果length属性为0 ,则将其强制为false (请参阅: Falsy values )。

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

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