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 appropria
Solution 1:
You probably can use something in the lines of
const replacedValues = distances.reduce((acc, d) => {
const regex = newRegExp(`${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.
constreplaceDistances = data =>
distances.reduce(
(acc, d) => acc.replace(newRegExp(`,${d.label},`, "g"), `,${d.value},`),
data
);
// And whenever you load valuesthis.setState({
csvData: replaceDistances(reader.result) // or sampleData
})
Post a Comment for "How To Substitute Array Value In React.js?"