Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concat all values of a key from array of json object in react

Below is the JSON structure.

[
  {
    "severity": 1,
    "message": "msg1"
  },
  {
    "severity": 2,
    "message": "msg2"
  }
]

This is the response i’m getting from backend API and I have to concatenate all messages in this array and display on the UI using ReactJs.

So, final output here would be "msg1,msg2".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can iterate over this array and then concatenate the strings, but is there a way in which we can concatenate with in-build function.

>Solution :

This is how to build it as a component in React:

import React from 'react';

const YourComponent = ({ data }) => {
  // Assuming 'data' is your array of JSON objects
  const concatenatedMessages = data.map(item => item.message).join(',');

  return (
    <div>
      {/* Display the concatenated messages */}
      <p>{concatenatedMessages}</p>
    </div>
  );
};

export default YourComponent;

Also you can use the useState and useEffect hooks if you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading