1

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.

kyun
  • 9,710
  • 9
  • 31
  • 66
  • 6
    `
    {filteredCardMemberData.join(', ')}
    `
    – Hassan Imam Feb 22 '23 at 08:41
  • It is rendering output as below [object Object], [object Object] – Purva Parulekar Feb 22 '23 at 09:16
  • Hi, @Purva Parulekar try this [**Code sandbox**](https://codesandbox.io/s/mystifying-hugle-z0tk89?file=/src/App.js) and also see my answer for better understanding. – DSDmark Feb 22 '23 at 09:52
  • Does this answer your question? [How to build/concatenate strings in JavaScript?](https://stackoverflow.com/questions/31845895/how-to-build-concatenate-strings-in-javascript) – DSDmark Feb 22 '23 at 10:12

4 Answers4

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>;
NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22
1
const DisplayData = filteredCardMemberData.map(
  (info) => (
    // eslint-disable-next-line react/jsx-key -- disabling eslint rule
    <div> {info.productDescription}</div>
  )
).join(', ');
Arman
  • 641
  • 4
  • 12
0

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(',')
);
0

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

DSDmark
  • 1,045
  • 5
  • 11
  • 25