In this javascript destructuring object tutorial i wil show you details that how we can destructuring object in javascript. Javascript object destructuring is a useful JavaScript feature to extract properties from objects and bind them to variables. You will also learn destructuring nested objects in Javascript from this example.
Did you know that object destructuring can extract multiple properties in one statement, can access properties from nested objects, and can set a default value if the property doesn’t exist yet in your object.
Let's take a look
var Team = {
name: 'Brasil',
favorite: 'Neymar'
};
var name = Team.name;
var favorite = Team.favorite;
name; // => 'Brasil',
favorite; // => 'Neymar'
Look this is the way we access our object value without obejct destructuring.
Here Team.name
value is assigned to the variable name. Same way Team.favorite.
Now what have to do if we wanna access it using object destructuring
var Team = {
name: 'Brasil',
favorite: 'Neymar'
};
const { name, favorite } = Team;
name; // => 'Brasil',
favorite; // => 'Neymar'
Here const { name, favorite } = Team
is an object destructuring assignment. If we want to destructure the object into multiple properties, enumerate as many properties as you like adding commas ,
in-between:
const { identifier1, identifier2, ..., identifierN } = expression;
Sometimes you need to destructured object doesn’t have the property specified in the destructuring assignment, then the variable is assigned with undefined
. Let’s see how it happens:
var Team = {
name: 'Brasil',
favorite: 'Neymar'
};
const { another } = Team;
another; // => undefined
So you can define default value like that
var Team = {
name: 'Brasil',
favorite: 'Neymar'
};
const { another = ['Casemiro'] } = Team;
another; // => ['Casemiro']
Now, instead of being undefined
, the variable another
defaults to ['Casemiro']
. Hope it can help you ...
#javascript