Skip to content

Instantly share code, notes, and snippets.

@ManojSatishkumar
Last active February 23, 2021 11:03
Show Gist options
  • Save ManojSatishkumar/dcc88dc2fa02e09e934df2d193a480cc to your computer and use it in GitHub Desktop.
Save ManojSatishkumar/dcc88dc2fa02e09e934df2d193a480cc to your computer and use it in GitHub Desktop.
Example Object traversal
// βœ… 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