将reduce()方法转换为map()方法

时间:2019-02-07 05:00:25

标签: javascript reactjs csv dataframe reduce

我想对_processData()函数使用map()方法来提取我的CSV文件的LATITUDE和LONGITUDE列,但不确定如何。我正在使用d3-fetch在CSV文件中进行解析。

  class App extends Component {
    state = {
      points: [],
    }

    componentDidMount() {
      this._processData()
    }

    _processData() {
      csv(csvFile).then(x => {
        const points = x.reduce((accu, curr) => {
          accu.push({
            position: [Number(curr.LONGITUDE), Number(curr.LATITUDE)],
            pickup: true,
          })
          return accu
        }, [])
        this.setState({
          points,
        })
      })
    }
    
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

1 个答案:

答案 0 :(得分:3)

您可以简单地执行以下操作:

_processData() {
  csv(csvFile).then(x => {
    const points = x.map(curr => ({
      position: [Number(curr.LONGITUDE), Number(curr.LATITUDE)],
      pickup: true,
    }));
    this.setState({
      points,
    })
  })
}