JavaScript Destructuring an object means assigning the properties of an object to individual variables. It is a useful JavaScript feature to extract properties from objects and bind them to variables.
let { property1: variable1, property2: variable2 } = object;
The identifier before the colon (:
) is the property of the object and the identifier after the colon is the variable.
JavaScript Destructuring object
Simple example code extracts some properties of an object.
<!DOCTYPE html>
<html>
<body>
<script>
var hero = {
name: 'Batman',
realName: 'Bruce Wayne'
};
// OLD
const n = hero.name;
const rName = hero.realName;
// is equivalent to:
const { name, realName } = hero;
console.log(n,rName)
</script>
</body>
</html>
Output:
Assigning to existing variable names
var employee = { // Object we want to destructure
firstname: 'Jon',
lastname: 'Snow',
dateofbirth: '1990'
};
// Destructuring the object into our variables
var { firstname, lastname, dateofbirth } = employee;
console.log( firstname, lastname, dateofbirth);
Assigning to new variable names
var employee = {
firstname: 'Jon',
lastname: 'Snow',
dateofbirth: '1990'
};
var { firstname: fn, lastname: ln, dateofbirth: dob } = employee;
console.log( fn, ln, dob);
Assigning to a variable with default values
var employee = {
firstname: 'Jon',
lastname: 'Snow',
dateofbirth: '1990'
};
var { firstname, lastname, country } = employee;
console.log( firstname, lastname, country);
var { firstname = 'default firstname',
lastname = 'default lastname',
country = 'default country' } = employee;
console.log( firstname, lastname, country);
Do comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version