I have a simple React/Spring Boot application where I want to populate a dropdown based on what's returned from an API call (a list of names, e.g "o1", "o2", "o3").
It can fetch and list the names as follows:
const templateOptionsTemp = await (await fetch(API_HOST + `/api/templates/`, {
credentials: 'include'
})).json();
templateOptionsTemp.map((templateName) =>
console.log("templateName: " + templateName)
);
Now, I just need to create a json object based on the name that looks like this:
{ key: 'o1', text: 'opt 1', value: 'o1'}
and add it to the array to be used as a dropdown, which is currently like this:
const templateOptions = [
{ key: 'o1', text: 'opt 1', value: 'o1' },
{ key: 'o2', text: 'opt 2', value: 'o2' },
{ key: 'o3', text: 'opt 3', value: 'o3' },
]
So the code would have to be something like this:
const tempArray = []
templateOptionsTemp.map((templateName) =>
const obj = {
'key': templateName,
'value': templateName,
'text': templateName
}
templateOptionsTemp.push(obj);
);
this.setState(templateOptions: tempArray);
But, I'm getting a syntax error on the above code - apparently you can't add more than one statement to the "map" function. The error is saying the "," operator is expected. If I add brackets, the error message says a return value is expected.
How do I get this to work? I just need to populate the templateOptions in the app's state.
.map()will build a new array for you based on what you return from its callback. What you're doing here is building an array outside of your.map()method and then using.map()to iterate over yourtemplateOptionsTemparray - for iteration only.forEach()is better suited for that. Instead, you can returnobjin your map callback to "push" it to the new array map builds for you, and save that new array in a variable (eg: yeerk did this in their answer)