首页 > 解决方案 > 从对象数组中删除空对象

问题描述

我有一个对象数组和一个将索引作为参数传递但无法删除空对象的删除函数。可以删除包含属性的对象。有谁知道如何修理它?示例代码如下所示。

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

标签: javascriptarrays

解决方案


用于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)

上述工作,因为Object.keys将返回对象的属性数组。获取其length属性将获取数组中的项目数。如果length属性是0,它被强制为false(参见:Falsy values)。


推荐阅读