Reputation:
I am working with graphql returned data that looks like this:
"userRelations": [
{
"relatedUser": {
"id": 4,
"firstName": "Jack",
"lastName": "Miller"
},
"type": "FRIEND"
},
{
"relatedUser": {
"id": 3,
"firstName": "Rhena",
"lastName": "Tahoma"
},
"type": "CONTACT"
}
]
I had to separate all those items which had the type: "FRIENDS"
. I did this and it worked perfectly:
var friendArray = new Array();
for (let i in data.users.nodes[0].userRelations) {
if (data.users.nodes[0].userRelations[i].type == "FRIEND")
{
friendArray.push(data.users.nodes[0].userRelations[i]);
}
}
However, I read that using for loops and for in is not a good idea. Is there any other way to iterate and check all the objects without for loops? I tried using this but it doesn't give the correct results:
data.users.nodes[0].userRelations.forEach((object: Object)=> {
if (data.users.nodes[0].userRelations.type == "FRIEND")
{
friendArray.push(data.users.nodes[0].userRelations.object);
}
})
The friendsArray remains empty. What am I missing out?
Edit: After filtering the friends data, I want to render some items by mapping. I was trying to do something like this:
data.users.nodes[0].userRelations.map()
data.users.nodes[0].userRelations.filter(({ type }) => type === 'FRIEND').map(/*code*/)
but this gave me an error that:
Binding element 'type' implicitly has an 'any' type.ts(7031)
Upvotes: 2
Views: 6372
Reputation: 2358
data.users.nodes[0].userRelations.forEach((o: Object)=> {
if (o.type == "FRIEND")
{
friendArray.push(o);
}
})
Upvotes: 0
Reputation: 3053
In your case I would use filter
:
var result = data.users.nodes[0].userRelations.filter(element=>element.type=="FRIEND");
Upvotes: 1
Reputation: 9591
Have a look at array.filter(), you can do const friends = data.users.nodes[0].userRelations.filter(userRelation => userRelation.type === 'FRIEND")
but to your current code, you could change your if statement to be - if(object.type==='FRIEND')
Upvotes: 0
Reputation: 481
First of all, using a for loop there is fine.
If you want to use foreach, you'll need to use the object element you create in the forEach callback. That's the advantage of using foreach.
data.users.nodes[0].userRelations.forEach((object: Object)=> {
if (object.type == "FRIEND")
{
friendArray.push(object);
}
})
If you want to improve the function, you may want to use a .filter, which is probably the cleanest way of solving this.
Upvotes: 0