如何映射外部JSON数据?

时间:2018-06-06 03:35:53

标签: javascript reactjs

我已将JSON数据保存为profiledata.js文件。我想映射每个对象并在页面上显示它。我知道.map()功能仅适用于array而非objects。所以我创建了一些对象,但仍然无法使用.map()在页面上显示数据。

profiledata.js:

const profiledata = [  {
        "_id": {
          "_str": "5b0761dc88430400064d9a31"
        },
        "batting": {
          "_id": {
            "_str": "54cc1859ce17393ab3219eda"
          },
          "avgRate": 43,
          "centuries": 0,
          "halfCenturies": 0,
          "highestScore": 43,
          "notOut": 0,
          "numInnings": 1,
          "numMatches": 1,
          "strikeRate": null,
          "teamid": {
            "_str": "54cc196cce17393ab321a9e6"
          },
          "totalBalls": 18,
          "totalFours": 2,
          "totalPoints": 78,
          "totalRuns": 43,
          "totalSixes": 5
        },
        "bowling": {
          "_id": {
            "_str": "54cc1859ce17393ab3219eda"
          },
          "bestInnings": {
            "runs": 39,
            "wickets": 0
          },
          "numMatches": 1,
          "runRate": 6.5,
          "totalBalls": 0,
          "totalMaidens": 0,
          "totalNoBalls": 1,
          "totalOvers": 6,
          "totalPoints": 5,
          "totalRuns": 39,
          "totalWickets": 0,
          "totalWides": 0
        },
        "division": "A",
        "fielding": [],
        "matches": 1,
        "player": {
          "_str": "54cc1859ce17393ab3219eda"
        },
        "points": 83,
        "season": "2018",
        "team": {
          "_str": "54cc196cce17393ab321a9e6"
        },
        "tournament": {
          "_str": "f4e8a58fd0d90574856d1a46"
        },
        "tournamentString": "f4e8a58fd0d90574856d1a46"
      },
    {},
    {},
    ....
    ];

    export default profiledata;

chart.js之:

import React, { Component } from 'react';
import profiledata from './profiledata';


class Chart extends Component {

  render(){
    return(
      <div>
          {profiledata.map( newdata => {
            return(
              <div>
            <li> {newdata._id}</li>
              </div>
            );
          })}

      </div>
    )}

}

export default Chart;

我正在尝试使用_id显示每个对象的.map()。我将profiledata导入到名为chart.js的组件中。检查截图: enter image description here

2 个答案:

答案 0 :(得分:2)

在输入个人资料数据时添加.js。 替换这一行

import profiledata from './profiledata';

import profiledata from './profiledata.js';

答案 1 :(得分:1)

当._id是包含&#39; _str&#39;的对象时,您正在调用newdata._id,这正是您想要的。

尝试,

newdata._id._str