Problem
You want to create an HTML list based on an array of objects.
Ingredients
- template strings
- the
map()
method
Directions
-
Given: an array of objects …
const persons = [ { firstName: 'John', lastName: 'Doe' }, { firstName: 'Jane', lastName: 'Doe' }, { firstName: 'Jane', lastName: 'Smith' }, { firstName: 'Dave', lastName: 'Smith' }, { firstName: 'Jane', lastName: 'Carpenter' } ]
… and you want to create a function
htmlList()
that takes this array …let result = htmlList(person);
… and creates the following HTML code:
<ul> <li>John Doe</li> <li>Jane Doe</li> <li>Jane Smith</li> <li>Dave Smith</li> <li>Jane Carpenter</li> </ul>
-
Create a function
htmlList()
that accepts an array and returns a template string.const htmlList = array => ``
-
Add the HTML code for the list to the template string.
const htmlList = array => `<ul></ul>`
-
Add an embedded expression between the
<ul>
and</ul>
tags.const htmlList = array => `<ul>${}</ul>`
-
Now create another function
htmlListItem()
that accepts an object and returns a template string containing the code for one single list item (using an embedded expression and returning the concatenation offirstName
andlastName
).const htmlListItem = object => `<li>${object.firstName + object.lastName}</li>` const htmlList = array => `<ul>${}</ul>`
-
Now inside the embedded expression in the
htmlList()
function call themap()
method on the array and pass thehtmlListItem()
function.const htmlListItem = object => `<li>${object.firstName + object.lastName}</li>` const htmlList = array => `<ul>${array.map(htmlListItem)}</ul>`
-
Finally join the result of the
map()
function using thejoin()
method …const htmlListItem = object => `<li>${object.firstName + object.lastName}</li>` const htmlList = array => `<ul>${array.map(htmlListItem).join('')}</ul>`
-
And adjust the formatting of the output:
const htmlListItem = object => ` <li>${object.firstName + object.lastName}</li>` const htmlList = array => `<ul>${array.map(htmlListItem).join('')} </ul>`
Alternatively you use
\n
and\t
to format the output:const htmlListItem = object => `\n <li>${object.firstName + object.lastName}</li>` const htmlList = array => `<ul>${array.map(htmlListItem).join('')}\n</ul>`
- Voilá, a delicious function that creates an HTML list based on an object array:
```javascript
console.log(htmlList(persons))
```
And the generated HTML code looks like this:
```html
<ul>
<li>JohnDoe</li>
<li>JaneDoe</li>
<li>JaneSmith</li>
<li>DaveSmith</li>
<li>JaneCarpenter</li>
</ul>
```
Notes
-
One limitation of the code shown is that it only works for arrays of person objects, i.e., for arrays of objects that have the properties
firstName
andlastName
, becausehtmlListItem()
depends on those properties.In tomorrow’s recipe we will see how to remove this coupling and adjust both the
htmlList()
and thehtmlListItem()
function to work with any type of objects.
Alternative recipes
- Use a template engine like EJS or Jade.