- Building Applications with Spring 5 and Vue.js 2
- James J. Ye
- 159字
- 2025-04-04 16:05:51
Object destructuring
First of all, let's see an example of object destructuring:
1. let user = {name:'Sunny', interests:['Traveling', 'Swimming']};
2. let {name, interests, tasks} = user;
3. console.log(name); // Sunny
4. console.log(interests); // ["Traveling", "Swimming"]
5. console.log(tasks); // undefined
As you can see, the name and interests variables defined in line 2 pick up the values of the properties with the same name in the user object. And the tasks variable doesn't have a matching property in the user object. Its value remains as undefined. You can avoid this by giving it a default value, like this:
let {name, interests, tasks=[]} = user;
console.log(tasks) // []
Another thing you can do with object destructuring is that you can choose a different variable name. In the following example, we pick the value of the name property of the user object and assign it to the firstName variable:
let {name: firstName} = user;
console.log(firstName) // Sunny