简体   繁体   中英

How to substitute array value in React.js?

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.

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
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM