How to useObject Destructuring in JSON

Object destructuring in TypeScript allows you to directly extract properties from an object and assign them to variables. You can use this technique to initialize a TypeScript object with a JSON object.

Example: In this example we parses a JSON string into an object, then extracts username and userAge using object destructuring, logging them.

JavaScript
let jsonString =
    '{"username": "GFG", "userAge": 22}';
let { username, userAge } =
    JSON.parse(jsonString);

console.log(username);
console.log(userAge);

Output
GFG
22


How to Initialize a TypeScript Object with a JSON-Object ?

To initialize a TypeScript Object with a JSON-Object, we have multiple approaches. In this article, we are going to learn how to initialize a TypeScript Object with a JSON-Object.

Below are the approaches used to initialize a TypeScript Object with a JSON-Object:

Table of Content

  • Object.assign
  • Type Assertion
  • Spread Operator
  • Class Initialization
  • Using Object Destructuring

Similar Reads

Approach 1: Object.assign

Object.assign method copies the values of all enumerable properties from one or more source objects to a target object....

Approach 2: Type Assertion

Type assertion is a way to tell the TypeScript compiler about the specific type of a variable when the type cannot be inferred automatically....

Approach 3: Spread Operator

The spread operator (…) is used for copying the properties of one object into another object....

Approach 4: Class Initialization

You can create a class with a constructor that takes a JSON object as a parameter and initializes the class properties....

Approach 5: Using Object Destructuring

Object destructuring in TypeScript allows you to directly extract properties from an object and assign them to variables. You can use this technique to initialize a TypeScript object with a JSON object....