AJAX - AJAX Data Transformation and Normalization

Introduction

AJAX applications frequently communicate with APIs and web servers to retrieve information without reloading the entire webpage. The data received from a server is commonly provided in JSON format, but different APIs may return data in different structures. One API may use first_name, another may use firstName, while another may return the user's complete name in a single name field.

AJAX Data Transformation and Normalization is the process of converting this incoming data into a consistent and predictable structure before the application uses or displays it. This makes the application easier to develop, maintain, and modify.

For example, an API may return:

{
  "first_name": "Rahul",
  "last_name": "Kumar",
  "user_age": 25
}

The application may transform it into:

{
  "firstName": "Rahul",
  "lastName": "Kumar",
  "age": 25
}

The application can then work with the transformed structure consistently, regardless of how the original API represents the information.

Why Data Transformation Is Needed

Different APIs often follow different naming conventions and data structures. A frontend application may need to communicate with several APIs, each designed by a different development team.

Consider three APIs that provide customer information.

The first API returns:

{
  "customer_name": "Anita",
  "customer_age": 28
}

The second API returns:

{
  "name": "Anita",
  "age": 28
}

The third API returns:

{
  "customer": {
    "details": {
      "fullName": "Anita",
      "years": 28
    }
  }
}

Although all three responses represent similar information, their structures are different.

Instead of writing separate frontend logic throughout the application for each response format, developers can transform the responses into one standard structure:

{
  "name": "Anita",
  "age": 28
}

The rest of the application can then work with this common format.

Data Transformation

Data transformation means changing the structure, names, types, or representation of received data into a format that the application needs.

Suppose an AJAX request retrieves employee information:

fetch("/api/employees")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

Assume the server returns:

{
  "employee_name": "Priya",
  "employee_salary": "45000"
}

The application may want the data in this form:

{
  name: "Priya",
  salary: 45000
}

The transformation can be performed using JavaScript:

const employee = {
  name: data.employee_name,
  salary: Number(data.employee_salary)
};

Here, two transformations take place.

First, employee_name is changed to name.

Second, the salary value is converted from a string into a number.

Data Normalization

Data normalization is the process of organizing data into a consistent structure so that similar information is represented in the same way throughout an application.

For example, an API might return these values:

[
  {
    "id": 1,
    "name": "Product A"
  },
  {
    "id": 2,
    "name": "Product B"
  }
]

Another endpoint might return:

[
  {
    "product_id": 3,
    "product_name": "Product C"
  }
]

A normalized application structure could be:

[
  {
    id: 1,
    name: "Product A"
  },
  {
    id: 2,
    name: "Product B"
  },
  {
    id: 3,
    name: "Product C"
  }
]

This gives the application a consistent way to access product information.

Basic AJAX Transformation Example

Consider an AJAX request:

const xhr = new XMLHttpRequest();

xhr.open("GET", "/api/users", true);

xhr.onload = function () {
  if (xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);

    const users = data.map(user => ({
      id: user.user_id,
      name: user.full_name,
      email: user.email_address
    }));

    console.log(users);
  }
};

xhr.send();

Suppose the server returns:

[
  {
    "user_id": 101,
    "full_name": "Arun Kumar",
    "email_address": "[email protected]"
  },
  {
    "user_id": 102,
    "full_name": "Meena Rao",
    "email_address": "[email protected]"
  }
]

The transformation produces:

[
  {
    id: 101,
    name: "Arun Kumar",
    email: "[email protected]"
  },
  {
    id: 102,
    name: "Meena Rao",
    email: "[email protected]"
  }
]

The user interface can now use id, name, and email without knowing the original API field names.

Handling Different Data Types

Transformation is also useful when an API returns values using inappropriate or unexpected data types.

For example:

{
  "price": "1500",
  "available": "true",
  "quantity": "10"
}

The application may need:

{
  price: 1500,
  available: true,
  quantity: 10
}

This can be achieved using:

const product = {
  price: Number(data.price),
  available: data.available === "true",
  quantity: Number(data.quantity)
};

This prevents problems during calculations or comparisons.

For example, adding two strings can produce unexpected results:

"100" + "50"

The result is:

10050

Whereas converting them to numbers produces:

Number("100") + Number("50")

Result:

150

Handling Missing Values

APIs may sometimes omit optional fields.

For example:

{
  "name": "Ravi",
  "email": "[email protected]"
}

The phone field may be missing.

A transformation layer can provide a default value:

const user = {
  name: data.name || "Unknown",
  email: data.email || "Not available",
  phone: data.phone || "Not provided"
};

This ensures that the application always receives a predictable structure.

A modern approach can also use nullish coalescing:

const user = {
  name: data.name ?? "Unknown",
  email: data.email ?? "Not available",
  phone: data.phone ?? "Not provided"
};

This is particularly useful when null or undefined values are returned by the server.

Converting Nested Data

APIs frequently return deeply nested objects.

For example:

{
  "customer": {
    "profile": {
      "personal": {
        "name": "Kiran",
        "age": 30
      }
    }
  }
}

The application may prefer:

{
  name: "Kiran",
  age: 30
}

Transformation can simplify the structure:

const customer = {
  name: data.customer.profile.personal.name,
  age: data.customer.profile.personal.age
};

The user interface does not need to understand the complicated structure of the original API response.

Normalizing Repeated Data

Normalization becomes especially useful when an API contains repeated objects.

Consider:

{
  "posts": [
    {
      "id": 1,
      "title": "AJAX Basics",
      "author": {
        "id": 10,
        "name": "Rahul"
      }
    },
    {
      "id": 2,
      "title": "AJAX Advanced",
      "author": {
        "id": 10,
        "name": "Rahul"
      }
    }
  ]
}

The same author information is repeated for every post.

A normalized representation could separate the entities:

const users = {
  10: {
    id: 10,
    name: "Rahul"
  }
};

const posts = {
  1: {
    id: 1,
    title: "AJAX Basics",
    authorId: 10
  },
  2: {
    id: 2,
    title: "AJAX Advanced",
    authorId: 10
  }
};

Now the author information exists only once.

This approach can make applications easier to update because changing the author's information does not require changing every individual post.

Creating a Transformation Function

Instead of performing transformations repeatedly, developers can create reusable functions.

function transformUser(user) {
  return {
    id: user.user_id,
    name: user.full_name,
    email: user.email_address,
    age: Number(user.user_age)
  };
}

The function can then be used after an AJAX request:

fetch("/api/users")
  .then(response => response.json())
  .then(data => {
    const users = data.map(transformUser);

    console.log(users);
  });

This separates API-specific processing from the rest of the application.

Benefits of AJAX Data Transformation and Normalization

Data transformation and normalization provide several important benefits.

Consistency: Different API response formats can be converted into one standard structure.

Simpler frontend code: UI components can work with predictable property names and data types.

Better maintainability: Changes in an API can often be handled in one transformation function rather than throughout the application.

Reduced duplication: Repeated information can be organized more efficiently.

Improved data validation: Data can be checked and converted before it reaches the user interface.

Easier integration: Applications can communicate with multiple APIs without forcing every part of the application to understand every API's unique structure.

Better separation of responsibilities: The API communication layer can handle external data formats while the application layer works with internal data structures.

Difference Between Transformation and Normalization

Although the two concepts are closely related, they are not exactly the same.

Transformation focuses on changing data from one representation into another.

For example:

first_name → firstName

or:

"500" → 500

Normalization focuses on creating a consistent and organized representation of related data.

For example, instead of storing the same user information repeatedly with every order, the application can store users separately and reference them by ID.

Therefore, transformation can be viewed as changing the format of data, while normalization focuses more on organizing data consistently and efficiently.

Practical AJAX Workflow

A typical application can follow this sequence:

AJAX Request
     |
     ↓
Server/API
     |
     ↓
Raw Response
     |
     ↓
Parse Response
     |
     ↓
Transform Data
     |
     ↓
Normalize Data
     |
     ↓
Validate Required Fields
     |
     ↓
Application Data Model
     |
     ↓
User Interface

This architecture prevents the presentation layer from becoming dependent on the exact structure of an external API.

Conclusion

AJAX Data Transformation and Normalization is an important technique for applications that consume data from APIs. AJAX retrieves the data, but the received data may not always be in the exact structure required by the application. Transformation changes field names, data types, nested structures, and formats, while normalization organizes related information into a consistent representation.

By placing a dedicated transformation and normalization layer between the AJAX response and the application, developers can create cleaner, more predictable, and maintainable web applications. It is particularly useful when an application communicates with multiple APIs or when external API structures differ from the application's internal data model.