I'm working on creating a JavaScript array that holds 3 elements:
var employees =
[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
To iterate through the data using a for
loop, you can use the following code:
for (let i = 0; i < employees.length; i++)
If you want to create a new <p>
element for each object and populate it with the data, you'll need to assign an id to each <p>
. Here’s how you can do that:
This is what your current code looks like:
<!DOCTYPE html>
<html>
<body>
<h2>JSON Java Syntax Examples</h2>
<script>
var employees =
[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
for (let i = 0; i < employees.length; i++)
{
document.createElement("p");
document.getElementById(i).innerHTML = employees[i].firstName + " " + employees[i].lastName;
}
</script>
</body>
</html>