Reputation: 408
I want to remove object from array if they dont have a value
i have the API A, that returns to me this JSON:
{
"code": 0,
"data": [
{
"name": {
"value": "Ana"
},
"fruit": {
"value": "Grape"
},
"from": {
"value": "BR"
}
},
{
"name": {
"value": "Michael"
},
"fruit": {
"value": "Apple"
},
"from": {
"value": "US"
}
}
]
}
and with the API B, i can return the id for this user passing her the name
i have this code:
getData() {
this.myService.getDataAPI_A()
.subscribe((res) => {
this.myList = res['data'];
if (this.myList) {
for (const key of this.myList) {
this.getId(key.name.value);
}
}
});
}
getId(name) {
this.myService.getDataAPI_B(name) // api B returns id with the name
.subscribe((res) => {
this.myList.map((tempList) => {
if (res.name === tempList.name.value) {
tempList.userId = res.id; // creating a key and setting value
return tempList;
}
return tempList;
});
});
}
then i got this json:
{
"code": 0,
"custodyBovespa": [
{
"name": {
"value": "Ana"
},
"userId": "43",
"fruit": {
"value": "Grape"
},
"from": {
"value": "BR"
}
},
{
"name": {
"value": "Michael"
},
"fruit": {
"value": "Apple"
},
"from": {
"value": "US"
}
}
]
}
Michael does not existe in my data base, so the api returns to me null, and for some reason dont create the key in my json (why?). after this i want to remove the object that dont have userId how i can do this?
Upvotes: 0
Views: 202
Reputation: 5530
As you said:
Michael does not existe in my data base
and the condition you set is
if (res.name === tempList.name.value) {
tempList.userId = res.id; // creating a key and setting value
return tempList;
}
return tempList;
As the your database doesn't have the the value 'Michael', The above condition is false. So, it gets out of the if clause and just return what it is without userId.
Now if you want to set the 'Michael' userId to null.
if (res.name === tempList.name.value) {
tempList.userId = res.id; // creating a key and setting value
} else {
tempList.userId = null;
}
return tempList;
Then filter out the data's using like @Rich answered.
console.log(data.filter(val => val['userId'] !== null);
Upvotes: 0
Reputation: 1636
If you'd like your resultant array to contain only objects that contain the property userId
, you can simply use plain JavaScript .filter
.
In my below example, I am removing any element that does not have a "userId"
prop.
var data = [
{
"name": {
"value": "Ana"
},
"userId": "43",
"fruit": {
"value": "Grape"
},
"from": {
"value": "BR"
}
},
{
"name": {
"value": "Michael"
},
"fruit": {
"value": "Apple"
},
"from": {
"value": "US"
}
}
];
var dataFiltered = data.filter(val => val["userId"]);
console.log(dataFiltered);
Upvotes: 3