I'm mapping data from a JSON to a React component, where part of the strings from the JSON are replaced by values from Context. This works perfectly for JSON that only has a single level.
This works:
/* JSON */
const data = {
"content":[
"#number# Tips to Get #goal#",
"Your Search For #goal# Ends Here"
]
}
const parameters = useContext(ParameterContext)
const {
audience,
goal,
number
} = parameters;
const content = data.content;
const listItems = content.map(
(result, index) =>
<li key={index}>{Object.keys(parameters).reduce((res, key) =>
res.replace(`#${key}#`, parameters[key]), result)}</li>
);
...
return (
<ul>
{listItems}
</ul>
)
However, when I introduce another level of nesting to my JSON data, the .map() function breaks. For example:
{
"content": [
{
"text" : "#number# Tips to Get #goal#",
"types" : [ "email"]
},
{
"text" : "Your Search For #goal# Ends Here",
"types" : [ "ad", "email" ]
}
]
}
Trying to parse that results in TypeError: res.replace is not a function. Now, I suspect that's because the target text strings are now inside another array, but I can't figure out how to reach them in my map() function.
How would I fix the map() function to read the text strings in the update JSON format?