JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<button id="price">
How much is a red apple?
</button>
<button id="brands">
List brands of red apples
</button>
<button id="count-brands">
How many brands are there?
</button>
JavaScript
var myObj = {
"fruits" : {
"apple" : {
"color" : "red",
"price" : "$0.49",
"brands" : ["brand-1", "brand-2", "brand-3"]
}
}
}
// handle the buttons
$("#price, #brands, #count-brands").on('click', function() {
switch (this.id) {
case "price":
alert('The price of a red apple is ' + myObj.fruits.apple.price);
break;
case "brands":
/* get the length of this array, then run through it, to concatinate
to a string variable */
// temp string to concatenate brands to
var tempString = "",
brandArrLen = myObj.fruits.apple.brands.length;
for (var i = 0; i < brandArrLen; i++) {
tempString = tempString + ' ' + myObj.fruits.apple.brands[i];
}
alert('The following brands for red apples are: ' + tempString);
break;
case "count-brands":
// part of same code above
var brandArrLen = myObj.fruits.apple.brands.length;
alert('There are ' + brandArrLen + ' brands of red apples');
break;
}
});