Destructuring and traversing of javascript objects
Destructuring
Destructuring is used to destructure existing objects into individual objects/data. Eg.
// ES6 method
var obj = {
"name":"Rusty",
"room":"kitchen",
"weapon": "candlestick"
}
let {name,weapon}=obj
console.log(name,weapon)
Traversing a nested Objects
Consider the following Object:
const game = {
"suspects": [
{
name: "Rusty",
color: "orange"
},{
name: "Scarlet",
color: "Red"
}
]
}
Function to iterate:
function traverse(obj) {
for ( let key in obj ){
console.log(key) //to print only key
console.log(obj[key]) // to print data of that key
}
}
traverse(game)
Output:
suspects
[
{ name: 'Rusty', color: 'orange' },
{ name: 'Scarlet', color: 'Red' }
]
Iterating Each element in the object:
function gameLoop(obj){
for (var i=0; i<obj.suspects.length; i++) {
for (key in obj.suspects[i]) { // for traversing array object
console.log(`${key} ${obj.suspects[i][key]}`) // printing value of array object
}
console.log()
}
}
gameLoop(game)
Output:
name Rusty
color orange
name Scarlet
color Red
Fun Task:
How to extract colors from the game
object using destructuring?
// Destructuring Orange and Red color from objects game
const [color1, color2] = [game.suspects[0].color, game.suspects[1].color]
console.log(color1,color2)
Alternate Way:
var [{color: firstcolor}, {color:secondcolor}] = game.suspects
console.log(firstcolor,secondcolor)