Javascript foreach like PHP?

Hi folks i am very new to js. Could you track me please how to foreach an array loop though and generate html from its content.

Array
(
    [0] => Array
        (
            [UserName] => Marcus
            [ProfileUrl] => ProfileUrl
            [AvatarUrl] => AvatarUrl
        )

    [1] => Array
        (
            [UserName] => David
            [ProfileUrl] => ProfileUrl
            [AvatarUrl] => AvatarUrl
        )

)

I would like to outout some like this:

<li>
<div><img src="AvatarUrl" /></div>
<div><a href="ProfileUrl">UserName</a></div>
</li>

For each element. And then append it to some ID

Hi @letsforum, why not use PHP then in the first place? ^^

Assuming you fetched some JSON data using AJAX though, you can use the forEach() array method and then insertAdjacentHTML() to the target element:

const target = document.getElementById('my-container-element')

myDataArray.forEach(item => target.insertAdjacentHTML('beforeend', `
  <li>
    <div><img src="${item.avatarUrl}"></div>
    <div><a href="${item.profileUrl}">${item.userName}</a></div>
  </li>
`))

PS: Or better, assemble the complete HTML and then insert it to the DOM at one go:

const target = document.getElementById('my-container-element')

const html = myDataArray.map(item => `
  <li>
    <div><img src="${item.avatarUrl}"></div>
    <div><a href="${item.profileUrl}">${item.userName}</a></div>
  </li>
`).join('')

target.insertAdjacentHTML('beforeend', html)
2 Likes

Thanks buddy. I use ajax post to get an array containing users data.

my array contains 100 user results. On load displaying 20 and then onclck show more show 20 more and so on.

I see, yes that makes sense then of course.

Amazing thanks so much. Gonna test it.

1 Like

Sorry buddy I get error: TypeError: GEOUsersData.forEach is not a function

I have stumbled upon this code seems to be working.

for (var key in GEOUsersData) {

  alert(GEOUsersData[key].UserName);

}

GEOUsersData.forEach(function(item){
  console.log('name: ' + item.UserName);
});

I would be careful with for / in though as this also includes enumerable properties in the protoype chain… if this is a plain array then this shouldn’t be a problem, but should generally be avoided for good practice.

Quite some time ago I found the W3Schools Ajax information, along with examples very helpful:

(https://www.w3schools.com/xml/ajax_php.asp)

I am currently using Ajax to dynamically query a MySql/Pdo database table and render results:

(https://this-is-a-test-to-see-if-it-works.tk)