I’m writing a small website on the Astro framework. I have a list of “Document Acceptance Points”. Previously, I just stored them in the variable offices = [ {} , {} , {} ]. I output them to the frontend as follows:
// Here the offices is an Array
<select size='2'>)
{ offices.map( (i) => <option value={i.id}> {i.name} </option> ) }
</select>
Now I am trying to do the same thing through Map().foreach() but nothing work:
// Offices.ts
const offices: Map<string, office> = new Map()
const volskaya: office = {
id: 'volskaya',
name: 'name',
address: 'address',
phone: '+x (xxx) xxx-xx-xx',
phoneUrl: 'tel:+xxxxxxxxxxx',
working: ''
}
const rabochaya: office = {
id: 'rabochaya',
name: 'name',
address: 'address',
phone: '+x (xxx) xxx-xx-xx',
phoneUrl: 'tel:+xxxxxxxxxxx',
working: ''
}
offices.set('volskaya', volskaya)
offices.set('rabochaya', rabochaya)
export {offices}
// Component.astro
---
import { offices } from "./offices";
---
<select>)
{ offices.forEach( (i) => <option value={i.id}> {i.name} </option> ) } // not working
</select>
At the same time, if I output the data to console.log(), everything displays as it should:
offices.forEach((i)=> console.log(i.id,i.name)) // working
I can’t understand it. Either there is some restriction on using Map(), or I am using Map() incorrectly.
>Solution :
What is rendered to the HTML is the result of offices.map and offices.forEach respectively.
Array.prototype.map returns an array of values (ie each value being the result of one execution of callback). In your case an array of HTML Elements (or at least something similar, I’m not familiar with Astro)
Map.prototype.forEach does also execute the callback for each element in the map, but it returns undefined … Thus there is nothing to render …