How to substitute array value in React.js?

泪湿孤枕 提交于 2019-12-13 03:09:26

问题


This is my sample code in React.js. I want to use an array distances from Constants.js in Main.js. In particular, the column APT in sampleData should be substituted by an appropriate value from an array distances taken from Constants.js.

Thus, after clicking on the button Load data, the object csvData should finally look as follows:

NUM,APT,COST
1,483,20
2,5777,25
3,5777,15

Constants.js

export const distances = [
  {label:"KJFK",value:5777},
  {label:"ERTE",value:483}
]

Main.js

import React, { Component } from 'react';
import { CsvToHtmlTable } from 'react-csv-to-table';
import ReactFileReader from 'react-file-reader';
import Button from '@material-ui/core/Button';
import {distances} from './Constants';

const sampleData = `
NUM,APT,COST
1,ERTE,20
2,KJFK,25
3,KJFK,15
`;

class CSVDataTable extends Component {

    state={
      csvData: sampleData
    };

    handleFiles = files => {
        var reader = new FileReader();
        reader.onload =  (e) => {
          // Use reader.result
          this.setState({
            csvData: reader.result
          })
          this.props.setCsvData(reader.result)
        }
        reader.readAsText(files[0]);
    }

    render() {
        return <div>
          <ReactFileReader
            multipleFiles={false}
            fileTypes={[".csv"]}
            handleFiles={this.handleFiles}>
            <Button
                variant="contained"
                color="primary"
            >
                Load data
            </Button>

          </ReactFileReader>
          <CsvToHtmlTable
            data={this.state.csvData || sampleData}
            csvDelimiter=","
            tableClassName="table table-striped table-hover"
          />
    </div>
    }
}

export default CSVDataTable;

I tried the following:

function myFunc(item, index) {
  if (item["APT"]=="ERTE") {
    return 483
  }
  else {
    return 5777
  }
}

this.setState({
   csvData: reader.result.forEach(myFunc)
})

But the code does not compile after this update.


回答1:


You probably can use something in the lines of

const replacedValues = distances.reduce((acc, d) => {
    const regex = new RegExp(`${d.label}`, 'g')
    return acc.replace(regex, d.value)
}, sampleData)

This will iterate over all the possible "distances", replace any value equal to distance.label with distance.value and return the final string with all the changes applied.

In your case you could then do

this.setState({
   csvData: replacedValues
})

Adding to this answer, you could create a function that dynamically replaces all values that match in a given string with the values from your distances constants.

const replaceDistances = data =>
  distances.reduce(
    (acc, d) => acc.replace(new RegExp(`,${d.label},`, "g"), `,${d.value},`),
    data
  );

// And whenever you load values

this.setState({
   csvData: replaceDistances(reader.result) // or sampleData
})


来源:https://stackoverflow.com/questions/57748318/how-to-substitute-array-value-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!