繁体   English   中英

从对象数组中删除空对象

[英]Remove empty object from array of objects

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

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

使用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 )。

暂无
暂无

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

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