2

I have this array tv, when I read this array with a loop for, it just give me the last item, in this case Toshiba, how can I do to it show me the TV brands??

for (var i=0;i<tv.length;i++){
            $('#item').html(tv[i].Brand)}
<div id='item'></div>

Array tv:

var tv = [{"Name":"TV","Brand":"Samsung"},
{"Name":"TV","Brand":"Toshiba"},
{"Name":"TV","Brand":"LG"}]

2 Answers 2

3

html() overwrites the content on each iteration, that's why only the last one is visible, the others are overwritten. You should be using append:

$('#item').empty();
for (var i=0; i<tv.length; i++){
    $('#item').append(tv[i].Brand);
}
Sign up to request clarification or add additional context in comments.

Comments

3

The problem: You have only one div#item element and you are updating its value in every iteration.

Solution: Dynamically create and append an element to show each item in the array like:

for (var i=0;i<tv.length;i++){
    $('<div/>').addClass('item').html(tv[i].Brand).appendTo('.container');
}

where:

  • item is a class - now that you have multiple elements
  • container - assumed to the parent element under which you want the items displayed

Comments