user1907121
user1907121

Reputation:

reading array json with javascript

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"}]

Upvotes: 2

Views: 78

Answers (2)

adeneo
adeneo

Reputation: 318352

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);
}

Upvotes: 3

techfoobar
techfoobar

Reputation: 66693

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

Upvotes: 3

Related Questions