首页 > 解决方案 > 通过 Json 响应流以查找匹配:.find 不是函数

问题描述

我习惯了用 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"
}

我正在尝试将团队的Winner市场概率呈现name为引导表。所以这意味着我必须遍历 JSON 输出,直到匹配名称Winner,然后遍历该过滤对象。

但是,我不知道streamJava 中该函数的 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

我必须做什么来渲染这张桌子?

标签: javascriptjsonreactjsreact-bootstrap

解决方案


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

你可以这样做:

// simulationResult is JSON

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

simulationResult.markets.find()

推荐阅读