<div id="items">Total number of items =</div>
</br>
JavaScript
var json = {
"Fruits": {
"Apples": "5",
"Oranges": "7"
},
"Vegetables": {
"Cabbage": {
"Type": "Rotten",
"Quantity": "7"
},
"Peas": {
"Type": "Fresh",
"Quantity": "9"
},
"Potatoes": {
"Type": "Rotten",
"Quantity": "4"
},
"Broccoli": {
"Type": "Fresh",
"Quantity": "3"
}
}
};
//Solve the following using code to manipulate the json object
// How many 'Fruits' do we have ?
/* A self executing function getting the string value of fruits and converting it into integer and adding those.
Return Value : An integer giving the total number of fruits in the json object */
var NumberOfFruits = (function () {
var count = 0;
if (json !== null) {
for (var fruit in json.Fruits)
count += parseInt(json.Fruits[fruit], 10);
} else {
count = -1;
console.log("Master! your json is not valid. Returning -1 instead");
}
return count;
})();
//alert("Fruits Count :" + NumberOfFruits);
//Uncomment the above line if you want to see the output in alert window
console.log("Fruits Count :" + NumberOfFruits);
// How many 'Fresh' 'Vegetables' do we have ?
var FreshVegetables = countVegetables(json.Vegetables, "Fresh");
//alert("Fresh Vegetables Count :" + FreshVegetables);
//Uncomment the above line if you want to see the output in alert window
console.log("Fresh Vegetables Count :" + FreshVegetables);
// How many 'Rotten Vegetables' do we have ?
var RottenVegetables = countVegetables(json.Vegetables, "rotten");
//alert("Rotten Vegetables Count :" + RottenVegetables);
//Uncomment the above line if you want to see the output in alert window
console.log("Rotten Vegetables Count :" + RottenVegetables);
/* A function to calculate the total number of vegetable of specified category. If no category is specified it...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.