首页 > 解决方案 > 删除嵌套数组中的空对象

问题描述

我有一个数组

const exampleArray = [
    {
     id: 1,
     name: test
    },
    {
     id: 1,
     name: test
    },
    {
    },
]

现在该数组exampleArray位于另一个对象数组中,所以

const exampleNest = [{
    property1: {},
    property2: [],
    exampleArray: [{...}],
}]

我需要删除里面的空对象exampleArray并返回数组的其余部分。

我已经尝试过使用过滤器

const noEmptyObjects = exampleNest.filter(({ exampleArray }) =>
    exampleArray.filter(attachment => attachment !== {}),
  );

我也尝试过Object.keys(attachment).length !== 0attachment !== {}但我继续收到带有空项目的数组。

标签: javascriptarraysobject

解决方案


您可以使用简单的https://stackoverflow.com/a/32108184/3932166来检查空对象和数组。

exampleArray.filter(attachment => (condition from above link));

推荐阅读