Home > front end >  How to extract Name from a JSON Name/Value pair and append to a TextField
How to extract Name from a JSON Name/Value pair and append to a TextField

Time:05-20

I have JSON which looks like this:

{
  "Id": 1,
  "Title": "Data about John Doe",
  "Comments": "Some text goes here",
  "UpdatedBy": "John Doe",
  "UpdateDate": "Apr 14 2022 12:00AM"
}

I want to map this JSON to MUI TextFields with the names of the name/value pairs as the TextField labels, and the values as the TextField values. I also need to be able to edit the values.

This is my array of data:

const [singleSizing, setSingleSizing] = useState("");
const fetchSizingData = async (intake_id, sizing_id) => {
  setSingleSizing(
    await fetch(`/api/fiscalyears/FY2023/intakes/${params.id}/details/questions`).then((response) =>
                response.json()
            )
  );
};

These are the Text Fields I am using:

<TextField
  value={}
  label={}
/>

CodePudding user response:

Assuming singleSizing is one JSON object. If not, map over first:

You can use Object.entries to extract the key/value pair from the object and then .map() over the entries to create the components.

// ...

  return Object.entries(singleSizing).map(sizingEntry => {
      const [label, value] = sizingEntry; // e.g. ['Title', 'Data about John Doe']
      
      return <TextField label={label} value={value} />
  });

// ...

To edit the values, look into a MUI form components or another form library and consider changing the shape of the state to make updates easier.

CodePudding user response:

You can use .map & Object.keys

 {
     
      
        Object.key(obj).map(key => ( 
          <TextField 
              value = {
                obj[key]
              }
              label = {
                key
              }
            />
        ))
      
 }


  • Related