JavaScript Arrays Read Objects with forEach

This post works with an array of objects and uses the forEach() method of Arrays to read and display the objects in the browser after the user invokes the function by clicking the button. It also writes to the browser console.

<!DOCTYPE html>
<h1>JavaScript Arrays</h1>
<p>Displaying an object.</p>
<button onclick="fruits.forEach(myFunction)">Display Fruits</button>
<p>Name => Value</p>
<p id="demo"></p>
// display the objects when user clicks button
var demoP = document.getElementById("demo");
var fruits = [ { name:"Banana", value:3 },
               { name:"Orange", value:2 },
               { name:"Apple", value:7 }, 
			   { name:"Mango", value:4 } 
function myFunction(item) {
    console.log( + " => " + item.value);  // F12 in Chrome displays console
    demoP.innerHTML = demoP.innerHTML + + " => " + item.value + "<br />";

Below is the output in the browser after the user clicks the “Display Fruits” button one time.


If the user clicks the button a second time the list will be written again, under the first list.

Leave a comment

Your email address will not be published. Required fields are marked *