打字稿中的forEach函数

时间:2020-06-10 22:02:38

标签: javascript reactjs typescript react-native foreach

我正在处理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)

4 个答案:

答案 0 :(得分:1)

data.users.nodes[0].userRelations.forEach((o: Object)=> {
    if (o.type == "FRIEND")
    {
        friendArray.push(o);
    }
})  

答案 1 :(得分:1)

在您的情况下,我将使用filter

var result = data.users.nodes[0].userRelations.filter(element=>element.type=="FRIEND");

答案 2 :(得分:0)

首先,使用for循环就可以了。

如果要使用foreach,则需要使用在forEach回调中创建的object元素。这就是使用foreach的优势。

data.users.nodes[0].userRelations.forEach((object: Object)=> {
    if (object.type == "FRIEND")
    {
        friendArray.push(object);
    }
})  

如果要改进功能,则可能需要使用.filter,这可能是解决此问题的最干净的方法。

答案 3 :(得分:0)

看看array.filter(),您可以执行const friends = data.users.nodes[0].userRelations.filter(userRelation => userRelation.type === 'FRIEND"),但对于当前代码,可以将if语句更改为-if(object.type==='FRIEND')