简体   繁体   中英

Find the highest value key in an object, then post it to an innerHTML

I have an object that i'm tallying quiz question results in.

var answerData = {
    "Ninja": { score: 4 },
    "Robot": { score: 1 },
    "Pirate": { score: 7 },
    "Zombie": { score: 2 }
}

I'd like to determine which attribute is the highest then post the results to the page.

I found a post here on stackoverflow that suggested using object.reduce() to get a final result. I can't get it to return the highest value of 'pirate', instead it returns the last value of 'zombie'.

  function finalResults {
        theAnswer = Object.keys(answerData).reduce(function(a, b){ return answerData[a] > answerData[b] ? a : b });

        document.getElementById("finalResulthere").innerHTML = "<p>Congratulations you are a " + theAnswer +".</p>";
}

To then post it to

<div id="results">
  <div id="finalResulthere"></div>
</div>

My alternative thoughts were to run chained IF statements comparing the values of each of the object keys. This appeared to be neater...

You function is almost complete, you just miss a detail, you are comparing the complete object and it always fail.

function finalResults() {
    var theAnswer = Object.keys(answerData).
                reduce(function(a, b){ 
                   return answerData[a].score > answerData[b].score ? a : b }
                );

    document.getElementById("finalResulthere").innerHTML = "<p>Congratulations you are a " + theAnswer +".</p>";
}

you need to compare using the value of the score property, that is what you are missing

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