我正在获取值作为输入并将它们作为数组推送到后端。前端的 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/