Reputation: 85
I am getting values as input and pushing them as an Array to the back end. There are 6 predefined items in the Array in the front end. If I send 6 values there won't be any empty elements inside the array. If I send less than 6 it's creating an empty element. That's a known fact. Now I want to filter out the empty elements before pushing the array.
Actual output
[
{
"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)
);
}
Upvotes: 1
Views: 769
Reputation: 1210
You can use filter method and filter array based on property count in each item like follows
this.abcService.addabc(ABC).subscribe(
res => {
let res1 = res.filter(i=>Object.keys(i.ABC_Info.ABC).length >1);
this.abcArray.push(res1); //abcArray is a array. Before Pushing I want to check for empty element and remove before pushing
},
error => console.log(error)
);
}
filter array element without any property like _id you can use
res.filter(i=>Object.keys(i.ABC_Info.ABC).length >0);
Upvotes: 1
Reputation: 10384
You want to know if the object is empty besides the _id
property, so you can do something like this:
res.ABC.filter(obj => {
const keys = Object.keys(obj);
return (keys.length !== 1 || keys[0] !== '_id') && keys.length !== 0;
});
Upvotes: 2
Reputation: 2171
You can use array filter :
this.abcArray = res.ABC.filter(result => result.a && result.b && result.c);
Upvotes: 1
Reputation: 7456
You need to use the filter method on your array if you'd like to make it after you have the data:
this.abcArray.filter(item => ...your predicate to say an item is non-empty...)
If you can control when the items are pushed or not, why don't you simply push them just when you know they are non-empty?
if (... your predicate non empty ...)
this.abcArray.push(res)
Upvotes: 3