我正在使用 graphql 返回的数据,如下所示:
"userRelations": [
{
"relatedUser": {
"id": 4,
"firstName": "Jack",
"lastName": "Miller"
},
"type": "FRIEND"
},
{
"relatedUser": {
"id": 3,
"firstName": "Rhena",
"lastName": "Tahoma"
},
"type": "CONTACT"
}
]
我必须将所有带有
type: "FRIENDS"
的项目分开。 .我这样做了,而且效果很好: 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]);
}
}
但是,我读到使用 for 循环和 for in 不是一个好主意。有没有其他方法可以在没有 for 循环的情况下迭代和检查所有对象?我尝试使用它,但它没有给出正确的结果:
data.users.nodes[0].userRelations.forEach((object: Object)=> {
if (data.users.nodes[0].userRelations.type == "FRIEND")
{
friendArray.push(data.users.nodes[0].userRelations.object);
}
})
FriendsArray 保持为空。我错过了什么?
编辑:
过滤好友数据后,我想通过映射来渲染一些项目。我试图做这样的事情:
data.users.nodes[0].userRelations.map()
data.users.nodes[0].userRelations.filter(({ type }) => type === 'FRIEND').map(/*code*/)
但这给了我一个错误:
Binding element 'type' implicitly has an 'any' type.ts(7031)
最佳答案
在你的情况下,我会使用 filter
:
var result = data.users.nodes[0].userRelations.filter(element=>element.type=="FRIEND");
关于javascript - typescript 中的 forEach 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62313858/