Processing an array of JSON objects
This is a simple example that shows how to process an array of JSON objects.
HTML
<!-- division for the report -->
<div id="report"></div>
<!-- Menu for the colour -->
<select id="colour" >
<option>red</option>
<option>black</option>
<option>white</option>
</select>
<!-- Menu for the Make -->
<select id="make" >
<option>Ford</option>
<option>Honda</option>
<option>Toyota</option>
<option>Honda</option>
</select>
<button onclick="generateReport()">Submit</button>
JavaScript
// Here is inventory on the car lot
var cars = [
{make: "Ford", colour: "red", },
{make: "Holden", colour: "white" },
];
// Count how many cars there are of a certain colour and make
function howMany(colour, make) {
var count = 0;
for (var i=0 ; i<cars.length ; i++) {
if (cars[i].make == make && cars[i].colour == colour) {
count++;
}
}
return count;
}
// Generate a report showing the
// nubmer of cars with a given colour and make combination
function generateReport() {
var theMake = document.getElementById("make").value;
var theColour = document.getElementById("colour").value;
var theCount = howMany(theColour, theMake);
var verb = "are";
var plural = "s";
if (theCount == 1) {
verb = "is";
plural = "";
}
var htmlText = "<p> There " + verb + " " + theCount + " " + theColour + " " + theMake + plural;
document.getElementById("report").innerHTML = htmlText;
}