javascript - 从对象数组中删除空对象
问题描述
我有一个对象数组和一个将索引作为参数传递但无法删除空对象的删除函数。可以删除包含属性的对象。有谁知道如何修理它?示例代码如下所示。
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)。
推荐阅读
- javascript - vuejs 如何将 v-slot 引用移动到组件中?
- java - 使用递归在 char[] 中查找特定字符后跟另一个特定字符
- c - 切片字符串和字符缓冲区不相等
- python - 无法在 Selenium 自动化工具中获取 span 元素中的每个单词?
- javascript - 使用数组道具更新不正确的反应子组件
- reactjs - axios API 调用未触发
- node.js - 蒙聚合直接返回文档数组
- flutter - 删除默认启动屏幕 android & ios flutter
- bash - 为什么 ''rm "$dir"/* !(.gitignore)'' 会删除脚本本身?
- javascript - 无法预先添加使用 jQuery 单击的 div