Last active
February 23, 2021 11:03
-
-
Save ManojSatishkumar/dcc88dc2fa02e09e934df2d193a480cc to your computer and use it in GitHub Desktop.
Example Object traversal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// β Object Traversal in javascript | |
// π€ We will traverse this horse object and its methods | |
const horse = { | |
color: "Black", | |
name: "Razor", | |
behaviour: { | |
actionTypes: { | |
moveMethods: ["twist", "Jump", "Run"], | |
twistAction() { | |
console.log("Moved now"); | |
}, | |
jumpAction() { | |
console.log("Jumped now"); | |
} | |
}, | |
mood: "angry", | |
ears: "closed" | |
} | |
} | |
// π» Method to traverse the horse object | |
// We will use the π‘for...in loop | |
const traverseObj = (horse) => { | |
for (let prop in horse) { | |
if (typeof horse[prop] === 'object') { | |
traverseObj(horse[prop]) | |
} else if (typeof horse[prop] === 'function') { | |
horse[prop](); | |
} | |
else { | |
console.log(horse[prop]); | |
} | |
} | |
} | |
traverseObj(horse); | |
// -------------------------------------------- | |
// πOutput | |
// -------------------------------------------- | |
// Black βββββ | |
// Razor | |
// twist ββββββ | |
// Jump | |
// Run βββββ | |
// Moved | |
// Jumped | |
// angry βββββ | |
// closed βββββ | |
// -------------------------------------------- | |
// ----------------------------- | |
// π MSK | Web development | |
// π¨βπ» Author - Manoj Satishkumar | |
// ----------------------------- | |
// β€ You should enjoy coding | |
// ----------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment