How to iterate through an array and render html

How to iterate through an array and render html
0.0 0

#1

I need help iterating through an array of objects and rendering out the html. I currently use jQuery in the following way, but I want to know of a more industry-standard way of accomplishing this. Also, if the answer is angular or react, I am amenable.

	arr_Pages.forEach(function( a) {
		var $nav= $( "<div/>", {
			id: 'nav-' + a.name,
			class: 'nav',
			html: a.nameNav,
         });
       $nav.appendTo($container);
});

Thanks in advance for your help!
Mike


#2

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

What you are doing is fine, though I prefer to iterate through the array and build the navigation bar and only update the DOM one time.

const nav = arr_Pages.reduce((html,page) => html += `<div id="${page.name}" class="nav">${page.nameNav}</div>`,'');
$container.append(nav);

#3

Thank you for your reply! Your concise answer has encouraged me to learn

  • reduce() function
  • arrow functions =>
  • template literals ${}

which i imagine is the point of the website, right? :wink:

As a followup question, I have to build for IE11. What is your preferred polyfill solution? Babel?

Mike


#4

I would look into using Babel for the template literals and arrow functions, but be mindful of the limitations. See the following compatibility table.

https://kangax.github.io/compat-table/es6/


#5

Thanks for your prompt reply. You’ve been very helpful!