skip to Main Content

I have below code

const DisplayData = filteredCardMemberData.map(
  (info) => (
    // eslint-disable-next-line react/jsx-key -- disabling eslint rule
    <div> {info.productDescription}</div>
  )
);

I gives the below output

Apple
Mango

I want to convert the output as

Apple, Mango

Also, I want "Apple, Mango" to be one string, all the data should be concatenated to only string and separated by comma(,).
Can you help me.

4

Answers


  1. For that you need to use .join().

    Your final code look like:

    const mainData = filteredCardMemberData.map((info) => info.productDescription);
    
    const finalData = mainData.join(', ');
    
    return <div>{finalData}</div>;
    
    Login or Signup to reply.
  2. const DisplayData = filteredCardMemberData.map(
      (info) => (
        // eslint-disable-next-line react/jsx-key -- disabling eslint rule
        <div> {info.productDescription}</div>
      )
    ).join(', ');
    
    Login or Signup to reply.
  3. You can use join method for this

    const DisplayData = filteredCardMemberData.map(
      (info) => (
        // eslint-disable-next-line react/jsx-key -- disabling eslint rule
        <div> {info.productDescription}</div>
      ).join(',')
    );
    
    Login or Signup to reply.
  4. If I’m correct then you are using ReactJS. Consider using React’s useMemo hook to memorize the result if the data is expensive to compute or frequently changes:

    import {useMemo} from 'react'
    
    const finalData = useMemo(() => {
      const mainData = filteredCardMemberData.map(
        ({productDescription}) => productDescription   // you can also access the value like this productDescription.value
      )
      return mainData.join(', ')
    }, [filteredCardMemberData])
    

    This will only recompute the data if the dependency array (in this case, filteredCardMemberData) changes. Here is some other info which I think you need to read: efficient way-to-concatenate-strings

    Here is Demo:- CodeSandBox

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search