Home  >  Article  >  Web Front-end  >  How to Convert Plain JSON Objects into Class Instances in JavaScript?

How to Convert Plain JSON Objects into Class Instances in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-18 12:25:30525browse

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:

  • JSON does not provide class information, so you must know the object structure beforehand.
  • It's recommended to move the run method to the Animal.prototype object rather than keeping it on each instance.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn