Skip to content
Advertisement

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

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.

Advertisement

Answer

You should only need 1 for each loop on your Div. You can uses the index to see if the corresponding array contains a value.

If you’re comparing with index, then the code should have an if statement to check data exists (to prevent possible null exceptions).

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

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

Output:

<div class="appendDiv">
    <h1>First</h1>
    <p>john</p>
</div>
<div class="appendDiv">
    <h1>Second</h1>
    <p>doe</p>
</div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement