'How to extract Name from a JSON Name/Value pair and append to a TextField
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={}
/>
Solution 1:[1]
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.
Solution 2:[2]
You can use .map & Object.keys
{
Object.key(singleSizing).map(key => (
<TextField
value = {
obj[key]
}
label = {
key
}
/>
))
}
Solution 3:[3]
case_when() is a bit of a code smell. The following base R idiom is simpler and uses %in%:
conds <- c("Conditions DEF", "HIJ") # add extra as required
df1$condition[df1$health_conditions %in% conds] <- "Condition"
Or, as suggested in the other answer, a regex might help:
df1$condition[grepl("Conditions", df1$health_conditions)] <- "Condition"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | dash2 |
