2

I'm using an HTML onclick event to call a function that will read a Javascript string containing JSON syntax and output the results, but only the last result is being shown.

var resorts = '{ "skiResorts" : [' +
    '{ "resortName":"Afton Alps" , "resortState":"Minnesota" },' +
    '{ "resortName":"Alpine Way" , "resortState":"Pennsylvania" },' +
    '{ "resortName":"Alyeska" , "resortState":"Alaska" } ]}';
var obj = JSON.parse(resorts);

function displaySkiResorts() {
    //code
    for (i = 0; i < obj.length; i++) {
        document.getElementById("req8").innerHTML = obj.skiResorts[i].resortName + " " + obj.skiResorts[i].resortState;
    }
}

Why doesn't this show the entire set of ski resorts?

4
  • 1
    why not use an object literal? Commented Feb 5, 2016 at 20:47
  • 1
    You need to provide more information; are there errors? Is it just printing out the wrong values? Commented Feb 5, 2016 at 20:47
  • obj.length == undefined. Commented Feb 5, 2016 at 20:48
  • 2
    Your obj is an object, not an array. So use obj.skiResorts.length Commented Feb 5, 2016 at 20:48

4 Answers 4

1

I changed the right acces to the array length obj.skiResorts.length, change the assignment to += and add a line break <br>.

var resorts = '{ "skiResorts" : [' +
         '{ "resortName":"Afton Alps" , "resortState":"Minnesota" },' +
         '{ "resortName":"Alpine Way" , "resortState":"Pennsylvania" },' +
         '{ "resortName":"Alyeska" , "resortState":"Alaska" } ]}';

var obj = JSON.parse(resorts);
function displaySkiResorts() {
    for (i = 0; i < obj.skiResorts.length; i++) { // obj.skiResorts.length right array
        document.getElementById("req8").innerHTML += obj.skiResorts[i].resortName + " " + obj.skiResorts[i].resortState + '<br>'; // += and <br> 
    }
}
displaySkiResorts();
<div id="req8"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Nina thank you, thank you!!!! The += was the key that I was missing (after so many helpful people pointed out that I needed to specify obj.skiResorts!!!). I am so JSON phobic that I literally go tharn like a Watership Down rabbit whenever I have to deal with it.
1

You have an error. You must itterate over obj.skiResorts but not obj So the result code would be

var resorts = '{ "skiResorts" : [' +
         '{ "resortName":"Afton Alps" , "resortState":"Minnesota" },' +
         '{ "resortName":"Alpine Way" , "resortState":"Pennsylvania" },' +
         '{ "resortName":"Alyeska" , "resortState":"Alaska" } ]}';

      var obj = JSON.parse(resorts);

      function displaySkiResorts() {
        //code
        for (i = 0; i < obj.skiResorts.length; i++) {
          document.getElementById("req8").innerHTML += obj.skiResorts[i].resortName + " " + obj.skiResorts[i].resortState + "<br />";
        }
      }

Comments

1

Nina's answer correctly points out both issues (that your loop condition is incorrect, and that you are overwriting the innerHTML of the output element on each iteration).

I wanted to point out an optimization. In the body of your loop, on each iteration, you

  1. lookup an element by ID, and
  2. modify its innerHTML which will cause the browser to re-render.

Both of these operations can be done once, outside the loop. Build-up the HTML you would like to insert into the output element, and do it in one operation, like so

var resorts = '{ "skiResorts" : [' +
    '{ "resortName":"Afton Alps" , "resortState":"Minnesota" },' +
    '{ "resortName":"Alpine Way" , "resortState":"Pennsylvania" },' +
    '{ "resortName":"Alyeska" , "resortState":"Alaska" } ]}';
var obj = JSON.parse(resorts);

function displaySkiResorts() {
    // build array of lines of HTML
    var length = obj.skiResorts.length;
    var html = new Array(length);
    for (var i = 0; i < length; i++) {
        html[i] = obj.skiResorts[i].resortName + " " + obj.skiResorts[i].resortState
    }

    // insert into output, separated by line breaks
    document.getElementById('req8').innerHTML = html.join('<br>');
}
displaySkiResorts();
<div id="req8"></div>

Comments

-1
for (i = 0; i < obj.skiResorts.length; i++) {
    document.getElementById("req8").innerHTML= obj.skiResorts[i].resortName + " " + obj.skiResorts[i].resortState;
}

As @putvande points out, you are overwriting the same element each time. It's not clear what you were trying to do there. Did you mean to concatenate them?

18 Comments

Maybe another thing to mention is that the innerHTML gets overwritten.
@MattBurland: If you know it's getting closed then you shouldn't answer. You can't just answer anyway, worse while throwing our quality limits out the window. That people answer off-topic questions is why people keep asking them!!! meta.stackexchange.com/q/133552/155739
@william.taylor.09: Closure is not about whether an answer was provided. It is about the quality of the question, and this question is lacking in an MCVE. Indeed, the problem statement as it currently stands is "it doesn't".
@PreferenceBean - It lacks a minimal example? I certainly shows an attempt to display a result from from in an html element. Perhaps you should review the closure reasons a little closer.
@PreferenceBean - Yes, I see your meta activity. I looked before I commented. It is actually very surprising to see you even discuss a meta issue in a comment thread like this since that is generally seen by the crowd at meta as inappropriate. And yet, here we are. There is a problem statement. The user has json. They parsed it. They attempted to iterate over it to display. It broke. They showed their attempt. It was recreateable. The title may be in need of changing, but the overall post is not in need of closure. Editing should take priority. You should know this.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.