Working with objects
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>New This</title>
<!-- Latest compiled and minified CSS & JS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body>
<h1>Open the console to see the action!</h1>
<script>
// Here we are given a cob-web of items. Let"s dig in and grab the items we need.
var theCobWeb = {
biggestWeb: {
item: "comb",
biggerWeb: {
items: ["glasses", "paperclip", "bubblegum"],
smallerWeb: {
item: "toothbrush",
tinyWeb: {
items: ["toenails", "lint", "wrapper", "homework"]
}
}
},
otherBigWeb: {
item: "headphones"
}
}
};
// Create the code necessary to print each of the following lines using the object above:
// "I found my glasses!"
// "I found my toothbrush!"
// "I found my headphones!"
// "I found my homework!"
console.log("I found my " + theCobWeb.biggestWeb.biggerWeb.items[0] + "!");
console.log("I found my " + theCobWeb.biggestWeb.biggerWeb.smallerWeb.item + "!");
console.log("I found my " + theCobWeb.biggestWeb.otherBigWeb.item + "!");
console.log("I found my " + theCobWeb.biggestWeb.biggerWeb.smallerWeb.tinyWeb.items[3] + "!");
// Bonus (Extra Hard): It"s impossible to complete this in the allotted time. Take this home as a challenge and bring it back to your TA/Instructor for the solution.
//Create a function using JavaScript (NOT jQuery) for which you can pass the name of an item and theCobWeb
// and the function returns the smallest web it was found inside of.
// Your code should work if someone were to modify theCobWeb.
// for example if you gave your program
// comb it should give back biggestWeb
// toenails it should give back tinyWeb
// headphones it should give back otherBigWeb
// HINT: you should use recursion
function isObject(o){
return typeof o == "object";
}
function findInObj(obj, itemName, webName){
for (key in obj){
if (key == "item"){
if (obj[key] == itemName){
console.log(webName);
}
}else if(key == "items"){
if (obj[key].indexOf(itemName) > -1){
console.log(webName);
}
}else{
if (isObject(obj[key])){
findInObj(obj[key], itemName, key); //recursion
}
}
}
}
//tests
//should console log biggestWeb
findInObj(theCobWeb, "comb", "theCobWeb");
//should console log tinyWeb
findInObj(theCobWeb, "toenails", "theCobWeb");
//should console log otherBigWeb
findInObj(theCobWeb, "headphones", "theCobWeb");
console.log("should have returned biggestWeb, tinyWeb, otherBigWeb");
</script>
</body>
</html>