'How to safely destructure a JavaScript object in TypeScript
I want to pull out attributes from a JavaScript object (below) but want to protect myself from either the object being null or undefined as well as the properties not existing. That is, I want the values to just be undefined and not have the JavaScript error.
const {id,username,userFirstName,userLastName} = attendeeResults;
Solution 1:[1]
You can use logical operators to achieve that:
const nullObject = null;
const { foo, bar } = nullObject || {};
console.log(foo, bar);
Solution 2:[2]
JavaScript allow you to define default value when destructuring an object. For example:
const {id: 0,username:'',userFirstName:'',userLastName:''} = attendeeResults;
But destruncturing throws an error if your attendeeResults object is null or undefined.
Solution 3:[3]
You could use the following, Please notice that i omitted username in the attendee to show that it keeps the null value.
const attendeeResults = { id: 1, userFirstName: 'John', userLastName: 'Smith'}
const obj = {
id: null,
username: null,
userFirstName: null,
userLastName: null
};
Object.assign(obj, attendeeResults);
console.log(obj);
Solution 4:[4]
This can be done this way:
const {id, username, ...rest} = {id: 10, username: 'u', firstname:'behzad',lastname:'besharati'};
console.log(id,username,rest);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | whynot |
| Solution 3 | Rafael Herscovici |
| Solution 4 | behzad besharati |
