Home > Enterprise >  How to remove commas from strings in an array?
How to remove commas from strings in an array?

Time:08-24

I need to remove commas which are in an array of odata objects. Each item has a description which sometimes contains commas. I need to remove those commas. Here is what I've attempted: Parent Component:

  <CSVComponent capxs={allCaps} />

Child Component:

import { CSVLink } from "react-csv";

export interface ICSVComponentProps {
    capxs: IListItem[];
}

export const CSVComponent: React.FunctionComponent<ICSVComponentProps> = (props: ICSVComponentProps) => {
    const [results, setResults] = React.useState([]);
   
    const headers = [
        { label: "Id", key: "id" },
        { label: "Title", key: "title" },
        { label: "Description", key: "description" },
    ];
 const getCaps = (c: IListItem[]) => {
        const results = [];
        for (let i = 0; i <= c.length - 1; i  ) {
            results[i] = {
                id: props.capxs[i].Id,
                title: props.capxs[i].Title,
                description: props.capxs[i].Description.replace(",",""),
            };
        }
        setResults(results);
    };

    return (
        <DefaultButton className={styles.csvButton}
        onClick={() => getCaps(props.capxs)}
        >
            <CSVLink data={results} headers={headers}>
                Create CSV
            </CSVLink>
        </DefaultButton>
    );

Update: I've updated the code sample above with the Parent component props pass down and more of the child component. Here is an image showing the array that is created and stored in state. This state is then used by react-csv:

enter image description here

The description value in each item in the array has the comma removed, but react-csv seems to ignore this and it detects the commas, therefore creating incorrect columns in the produced csv file.

CodePudding user response:

If I understand correctly what you need

const memoizedCaps = useMemo<IListItem[]>(() => {
    return caps.map(el => ({ ...el, description: el.description.replace(',', '') }));
}, [caps]);

const getCaps = () => {
    setResults(memoizedCaps);
};

CodePudding user response:

This issue has been resolved by using:

 const getCaps = (caps: IListItem[]) => {
        const results = [];
        for (let i = 0; i <= caps.length - 1; i  ) {
            results[i] = {
                description: props.capxs[i].Description.replace(/,/g, '""'),
            };
        }
        setResults(results);
    };

Not ideal but it's a limitation of react-csv. Ref: https://github.com/react-csv/react-csv/issues/176

Thanks for all your help.

  • Related