通过Json进行流式传输以查找匹配项:.find不是函数

问题描述 投票:0回答:1

我已经习惯于使用Java进行函数式编程,最近才刚开始尝试JS。我正在尝试流经看起来像这样的Json输出:

{
    "originatingRequest": {
        "clientId": 1,
        "simulationName": "Season 2020",
        "teamRatings": [{
                "teamId": 1,
                "rating": 2.5
            },
            {
                "teamId": 2,
                "rating": 0.85
            },
            {
                "teamId": 3,
                "rating": 1.35
            },
            {
                "teamId": 4,
                "rating": 1.35
            }
        ],
        "simulationId": "7d49cb14-d99e-4315-bba3-077d114ab6fc"
    },
    "markets": [{
            "name": "Winner",
            "selections": [{
                    "name": "Manchester City",
                    "probability": "0.25"
                },
                {
                    "name": "Manchester United",
                    "probability": "0.25"
                },
                {
                    "name": "Liverpool",
                    "probability": "0.25"
                },
                {
                    "name": "Chelsea",
                    "probability": "0.25"
                }
            ]
        },
        {
            "name": "Top Two",
            "selections": [{
                    "name": "Manchester City",
                    "probability": "0.95"
                },
                {
                    "name": "Manchester United",
                    "probability": "0.05"
                },
                {
                    "name": "Liverpool",
                    "probability": "0.95"
                },
                {
                    "name": "Chelsea",
                    "probability": "0.05"
                }
            ]
        }
    ],
    "created": "2020-05-27T11:12:43.467644"
}

我正在尝试将团队的Winnername市场概率渲染到引导表中。因此,这意味着我必须遍历JSON输出,直到匹配名称Winner,然后遍历该筛选对象。

但是,我不知道Java中与stream函数等效的Javascript。我确实对选项链接有所了解。这是我的尝试,使用find

function SimulationReport() {
  return (
    <Table>
      <thead>
        <th>Team Name</th>
        <th>Win Probability</th>
      </thead>
      <tbody>
        {simulationResult
          .find(t => t.originatingRequest.markets.name === "Winner")
          .selections.map(selection => (
            <tr key="">
              <td>{selection.name}</td>
              <td>{selection.probability}</td>
            </tr>
          ))}
      </tbody>
    </Table>
  );
}

不幸的是,这是我得到的错误:

TypeError: _api_model_simulationResult__WEBPACK_IMPORTED_MODULE_2__.find is not a function

我必须怎么做才能渲染这张桌子?

javascript json reactjs react-bootstrap
1个回答
1
投票

您不能在JSON对象上使用find,它应该是array

您可以执行以下操作:

// simulationResult is JSON

// simulationResult.originatingRequest.markets is array, so you can use find on it

simulationResult.originatingRequest.markets.find()
© www.soinside.com 2019 - 2024. All rights reserved.