Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6213

forEach function in typescript

$
0
0

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)

Viewing all articles
Browse latest Browse all 6213

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>