Object Parameter Destructuring

Today I've learnt about object parameter destructuring and I'm surprised I never knew about it till today. Its where you destructure an object into a function by directly entering the key within curly brackets.

Normal destructuring uses the normal format.

const {key1, key2} = object

However, when passing an object to a function, it can be clustering using the dot annotation just to get a specific key-value item, and that's where object parameter destructuring comes in.

const students = {name: "Joel" , Age: 20}

const myClass = ({ name })=>{console.log(name)}

myClass(students)

In this case, instead of passing the object *students* as a parameter to the function myClass then using dot annotation to get the value from the name key, we destructure it then pass on the key (in this case name) inside curly brackets. Its a cleaner and shorter way to destructure.

2 objects with the same key name

In the event where you have multiple objects both having the same key name, then you have to specify the key you want to use.

const student = {name: "Joel", age: 20}
const teacher = {name: "Rachel", age: 32}

function myClass ({ name : studentName}, {name : teacherName}) {
    console.log("Student: ", studentName)
    console.log("Teacher: ", teacherName)
}
myClass(student, teacher)