angular - 从数组中移除空元素

标签 angular typescript

我正在获取值作为输入并将它们作为数组推送到后端。前端的 Array 中有 6 个预定义项。如果我发送 6 个值,数组内将不会有任何空元素。如果我发送少于 6 个,它会创建一个空元素。这是众所周知的事实。现在我想在推送数组之前过滤掉空元素。

实际输出

[
    {

        "ABC_Info": {
            "_id": "5c404e2d16e42513905189a1",
            "ABC": [
                {
                    "_id": "5c404e2d16e42513905189a7",
                    "a": "Dosa",
                    "b": 15,
                    "c": 30
                },
                {
                    "_id": "5c404e2d16e42513905189a6",
                    "a": "Idly",
                    "b": 25,
                    "b": 25
                },
                {
                    "_id": "5c404e2d16e42513905189a5",
                    "a": "Vada",
                    "b": 25,
                    "c": 35
                },
                {
                    "_id": "5c404e2d16e42513905189a4"
                },
                {
                    "_id": "5c404e2d16e42513905189a3"
                },
                {
                    "_id": "5c404e2d16e42513905189a2"
                }
            ]
        }
    }
]

TS

this.abcService.addabc(ABC).subscribe(
    res => {
        this.abcArray.push(res); //abcArray is a array. Before Pushing  I want to check for empty element and remove before pushing

    },
    error => console.log(error)
);
}

最佳答案

您需要使用 filter method如果您想在获得数据后制作它,请在您的阵列上:

this.abcArray.filter(item => ...your predicate to say an item is non-empty...)

如果您可以控制何时推送或不推送项目,为什么不在知道它们非空时直接推送它们呢?

if (... your predicate non empty ...)
  this.abcArray.push(res)

关于angular - 从数组中移除空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54233919/

相关文章:

json - 如何使用 Elasticsearch 查询对象的键?

javascript - 如何使用货币管道获取组件中最多两位小数的值?

javascript - Angular HostListener 同一组件的多个实例

css - 在 Mat 表中无法指定表的高度并使页眉和页脚粘性

json - 如何将对象打印为 JSON 以在 Angular2 中进行控制台?

angular - 如何在 Angular2 中将数据发布到服务器?

node.js - 使用 cxsd 将 .xsd 转换为 TypeScript,cxsd 无法识别

css - Angular 4 CSS DIV 背景图像绑定(bind)不起作用

spring - 如何使用http从angular 4发送多部分文件

永远不会调用 Angular 启动服务工厂