Home > Article > Web Front-end > How to Convert Plain JSON Objects into Class Instances in JavaScript?
Casting Plain Objects to Class Instances in JavaScript
In JavaScript, when receiving plain objects from a server as JSON responses, you may encounter the need to cast them into typed class instances. This allows you to access class-specific methods and properties.
Solution:
One approach is to create a constructor that accepts any object resembling an instance and clones it. Alternatively, you can implement a static method that converts objects to instances:
<code class="javascript">Person.fromJSON = function(obj) { // Custom code to create an instance from the object return ...; };</code>
For your specific scenario, where you have plain objects with public properties, you can use the following method:
<code class="javascript">var personInstance = new Person(); for (var prop in personLiteral) { personInstance[prop] = personLiteral[prop]; }</code>
This assigns all properties from the plain object to the newly created instance. Similarly, you can create Animal instances.
Note:
Sample Code:
<code class="javascript">var persons = JSON.parse(serverResponse); for (var i = 0; i < persons.length; i++) { persons[i] = Object.assign(new Person(), persons[i]); // Use Object.assign for browsers that support it for (var j = 0; j < persons[i].animals; j++) { persons[i].animals[j] = Object.assign(new Animal(), persons[i].animals[j]); } }</code>
This code will enable you to use class-specific methods such as persons[0].Animals[2].Run();.
The above is the detailed content of How to Convert Plain JSON Objects into Class Instances in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!