简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM