Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map.prototype.forEach() does not work when creating html elements on Astro

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 …

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading