Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Linc's avatar
Level 1

Append array of object values if index is the same index of a div list.

Hi, I need help: I have one object with multiple array inside; i need to cycle all my array values and then append this values inside my HTML div list (with the same class). object[0] with div[0]; object[1] with div[1] ecc...

This is an example:

<!-- HTML -->

<body>
    
    <div class="appendDiv">
        <h1>First</h1>
    </div>

    <div class="appendDiv">
        <h1>Second</h1>
    </div>

</body>

⁄⁄JS

var values = [
    {
        'name': "john"
    },
    {
        'name': "doe"
    }
]

for (var i = 0; i < values.length; i++) {
    value = values[i];
    var name = value.name;
    
    $('.appendDiv').each(function(index, val){
        if (i === index) {
            $('.appendDiv').append('<p>' + name + '</p>');
        }
    })
}

But this method return to me with a wrong result like this:

First John Doe

Second John Doe

I need a result like this:

First (my first .appendDiv [0]) John (my first array name value [0])

Second (my second .appendDiv [1]) Doe (my second array name value [1])

Thank you.

0 likes
2 replies
MarianoMoreyra's avatar
Level 25

Hi @linc

The thing is that inside your .each() loop you are appending to the whole $('.appendDiv') collection of divs. Try with the following instead (no need for the second 'val' parameter I guess):

for (var i = 0; i < values.length; i++) {
    value = values[i];
    var name = value.name;
    
    $('.appendDiv').each(function(index){
        if (i === index) {
            $( this ).append('<p>' + name + '</p>');
        }
    })
}

Hope this helps!

1 like
Linc's avatar
Level 1

Thank you very much @marianomoreyra ! This is the right solution for me; thanks for the code and info about that.

Please or to participate in this conversation.