TypeScript Array of Objects

In TypeScript, an array of objects is a collection of items where each item is an object. Arrays of objects are commonly used to organize complex data structures, such as user information, products, or any other entity, into manageable collections.

In TypeScript, an array of objects is a collection of items where each item is an object. Arrays of objects are commonly used to organize complex data structures, such as user information, products, or any other entity, into manageable collections.

TypeScript allows us to perform various operations such as adding, removing, updating, and iterating over items on such arrays of objects. Let’s learn with examples.

1. Creating an Array of Objects

To create an array of objects in TypeScript, we define an array where each element is an object with properties that match the desired structure.

// Define an array of objects where each object represents an employee
let employees = [
  { name: "John", position: "Manager", age: 30 },
  { name: "Jane", position: "Developer", age: 28 },
  { name: "Alice", position: "Designer", age: 25 }
];

    To ensure type safety, we can explicitly define a type for the array of objects using interfaces or type aliases. This helps prevent errors by ensuring that all objects in the array conform to the defined structure.

    // Declare the Employee interface with an optional property 'age'
    interface Employee {
      name: string;
      position: string;
      age?: number;  // Optional property
    }
    
    // Declare the 'employees' array of type Employee
    let employees: Employee[];
    
    // Initialize the array with Employee objects
    employees = [
      { name: "John", position: "Manager", age: 30 },
      { name: "Jane", position: "Developer" },  // 'age' is optional here
      { name: "Alice", position: "Designer", age: 25 }
    ];

    2. Adding Objects to an Array

    To add objects to an array, we can use following methods:

    • push(): Adds one or more objects to the end of the array.
    • unshift(): Adds one or more objects to the beginning of the array.
    • splice(): Adds or removes objects at a specific index in the array.
    let employees = [
        { name: "John", position: "Manager" },
        { name: "Jane", position: "Developer" },
        { name: "Alice", position: "Designer" }
    ];
    
    // Using push() to add an object to the end
    employees.push({ name: "Bob", position: "Developer" });
    console.log("After push() :: " + JSON.stringify(employees));
    
    // Using unshift() to add an object to the beginning
    employees.unshift({ name: "Charlie", position: "Tester" });
    console.log("After unshift() :: " + JSON.stringify(employees));
    
    // Using splice() to add an object at index 1
    employees.splice(1, 0, { name: "Dave", position: "Tester" });
    console.log("After splice() :: " + JSON.stringify(employees));

    The program output:

    After push() :: [{"name":"John","position":"Manager"},{"name":"Jane","position":"Developer"},
    {"name":"Alice","position":"Designer"},{"name":"Bob","position":"Developer"}]
    
    After unshift() :: [{"name":"Charlie","position":"Tester"},{"name":"John","position":"Manager"},
    {"name":"Jane","position":"Developer"},{"name":"Alice","position":"Designer"},
    {"name":"Bob","position":"Developer"}]
    
    After splice() :: [{"name":"Charlie","position":"Tester"},{"name":"Dave","position":"Tester"},
    {"name":"John","position":"Manager"},{"name":"Jane","position":"Developer"},
    {"name":"Alice","position":"Designer"},{"name":"Bob","position":"Developer"}]

    3. Removing Objects from an Array

    We can remove the objects from an array of objects using the following methods:

    • pop(): Removes the last object from the array.
    • shift(): Removes the first object from the array.
    • splice(): Removes objects from a specific index.
    let employees = [
        { name: "John", position: "Manager" },
        { name: "Jane", position: "Developer" },
        { name: "Alice", position: "Designer" }
    ];
    
    // Using pop() to remove the last object
    employees.pop();
    console.log("After pop() :: " + JSON.stringify(employees));
    
    // Using shift() to remove the first object
    employees.shift();
    console.log("After shift() :: " + JSON.stringify(employees));
    
    // Using splice() to remove an object at index 0
    employees.splice(0, 1);
    console.log("After splice() :: " + JSON.stringify(employees));

    The program output:

    After pop() :: [{"name":"John","position":"Manager"},{"name":"Jane","position":"Developer"}]
    After shift() :: [{"name":"Jane","position":"Developer"}]
    After splice() :: []

    4. Updating Objects in an Array

    To update an object within an array, we can directly access the object by index and modifying its properties.

    let employees = [
        { name: "John", position: "Manager" },
        { name: "Jane", position: "Developer" },
        { name: "Alice", position: "Designer" }
    ];
    
    // Updating the position of the first object
    employees[0].position = "Senior Manager";
    
    // Updating the name of the second object
    employees[1].name = "Janet";
    
    console.log(JSON.stringify(employees));

    The program output:

    [
      { name: 'John', position: 'Senior Manager' },
      { name: 'Janet', position: 'Developer' },
      { name: 'Alice', position: 'Designer' }
    ]

    5. Iterating Over Objects in an Array

    To iterate over the array and access its objects, we can use the following methods:

    • forEach(): Executes a provided function once for each object in the array.
    • map(): Creates a new array with the results of calling a function on every object in the array.
    • for…of: A loop that iterates over the array, providing direct access to each object.
    let employees = [
        { name: "John", position: "Manager" },
        { name: "Jane", position: "Developer" },
        { name: "Alice", position: "Designer" }
    ];
    
    // Using forEach() to iterate
    employees.forEach(employee => {
        console.log(`${employee.name} - ${employee.position}`);
    });
    
    // Using map() to create a new array of names
    let employeeNames = employees.map(employee => employee.name);
    console.log(employeeNames);
    
    // Using for...of loop to iterate
    for (let employee of employees) {
        console.log(`${employee.name} is a ${employee.position}`);
    }

    The program output:

    John - Manager
    Jane - Developer
    Alice - Designer
    
    [ 'John', 'Jane', 'Alice' ]
    
    John is a Manager
    Jane is a Developer
    Alice is a Designer

    6. Summary

    This tutorial explained how to create and manipulate arrays of objects in TypeScript. We learned the methods used for key operations such as adding, removing, and iterating over elements in an array of objects, with examples.

    It also introduces how to print the array correctly after modifications using JSON.stringify() to display its content.

    Happy Learning !!

    Weekly Newsletter

    Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

    Comments

    Subscribe
    Notify of
    0 Comments
    Most Voted
    Newest Oldest
    Inline Feedbacks
    View all comments

    About Us

    HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

    It also shares the best practices, algorithms & solutions and frequently asked interview questions.