Click here to Skip to main content
15,902,929 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this multi-dimensional array in JavaScript and i'm trying to populate a header in HTML with it i want to populate this header so that all the first name is printed out separately in the header. Is there an easy way to accomplish this cos i'm not sure how to go about it. Any help would be greatly appreciated.

What I have tried:

Here is my JSfiddle[^]
Posted
Updated 20-Jun-18 1:54am

1 solution

There are a few ways to approach this, but many of the "shortcuts" will have unintended secondary effects. The best way to do this cleanly is to create the elements that you want to populate and append them into the DOM at your point of interest. For example:

HTML
<html>
<head>
    <script type="text/javascript">
        let personArr = [
            {firstName:"John", lastName:"Doe", age:21},
            {firstName:"Paul", lastName:"Logan", age:22},
            {firstName:"Sean", lastName:"Kim", age:32},
            {firstName:"Ken", lastName:"Chow", age:12}
        ];

        let peopleDiv = document.getElementById('People');

        for(let i=0;i<personArr.length;i++){
            let newElement = document.createElement('h6');
            newElement.innerHTML = personArr[i].firstName;
            peopleDiv.appendChild(newElement);
        }
    </script>
</head>
<body>
<div id="People"></div>
</body>
</html>


if you need to do this with a multi-dimensional array you can make your DOM assignments from a nested loop.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900