Typescript new array of objects

How to create an array of objects in TypeScript?

In TypeScript, the array contains the data or different values and can also contain an object. The object contains the properties and methods in TypeScript. We can access the object properties and invoke the object method by taking the object as a reference.

In this tutorial, we will learn to create an array of multiple objects in TypeScript. We will also learn to perform some operations, such as sorting on the array of objects.

Syntax

Here, we have given the syntax to follow to create the array of objects.

In the above syntax, Object_Type is a type of object that defines which properties all objects of the array will contain with its data type.

Example

In this example, we have used the type alias to create a type of object. The objType contains the obj_id of the number type and the obj_value of the string type.

We have created the array of objType objects containing the five different objects with different property values. Also, we are accessing the object from the first index and reading its property values.

// Creating the type for the object type objType = < obj_id: number; obj_value: string; >; // creating the array of objects let objArray: Array = [ < obj_id: 1, obj_value: "TutorialsPoint" >, < obj_id: 2, obj_value: "TypeScript" >, < obj_id: 3, obj_value: "Shubham" >, < obj_id: 4, obj_value: "TutorialsPoint" >, < obj_id: 5, obj_value: "TypeScript" >, ]; console.log( "The properties values of the object at the first index in objArray is " ); // accessing the object and its properties console.log(objArray[0].obj_id); console.log(objArray[0].obj_value);

On compiling, it will generate the following JavaScript code −

// creating the array of objects var objArray = [ < obj_id: 1, obj_value: "TutorialsPoint" >, < obj_id: 2, obj_value: "TypeScript" >, < obj_id: 3, obj_value: "Shubham" >, < obj_id: 4, obj_value: "TutorialsPoint" >, < obj_id: 5, obj_value: "TypeScript" >, ]; console.log("The properties values of the object at the first index in objArray is "); // accessing the object and its properties console.log(objArray[0].obj_id); console.log(objArray[0].obj_value);

Output

The above code will produce the following output −

The properties values of the object at the first index in objArray is 1 TutorialsPoint

Iterate Through The Array of Objects

We can use the loops to iterate through the array of objects. While iterating through the array, we can access the particular object using the zero-base array index. After accessing the object from the array, we can also access the object properties.

Syntax

Users can follow the syntax below to iterate through the array of objects.

In the above syntax, we have used the for-of loop to iterate through the array of objects. We can access the property by taking the obj as a reference.

Example

In this example, we used the for-of loop to iterate through the objects containing objects with different property values. In the for loop, we get a single object name obj, which we can use to access its property values.

// creating the array of objects let objArray = [ < obj_id: 1, obj_value: "TutorialsPoint" >, < obj_id: 2, obj_value: "TypeScript" >, < obj_id: 3, obj_value: "Shubham" >, < obj_id: 4, obj_value: "TutorialsPoint" >, < obj_id: 5, obj_value: "TypeScript" >, ]; console.log( «Iterating through the array of objects using the for-of loop and accessing its properties.» ); // using the for-of loop to iterate through the array of objects for (let obj of objArray)

Читайте также:  Определить уровень знания html

On compiling, it will generate the following JavaScript code:

// creating the array of objects var objArray = [ < obj_id: 1, obj_value: "TutorialsPoint" >, < obj_id: 2, obj_value: "TypeScript" >, < obj_id: 3, obj_value: "Shubham" >, < obj_id: 4, obj_value: "TutorialsPoint" >, < obj_id: 5, obj_value: "TypeScript" >, ]; console.log(«Iterating through the array of objects using the for-of loop and accessing its properties.»); // using the for-of loop to iterate through the array of objects for (var _i = 0, objArray_1 = objArray; _i

Output

The above code will produce the following output −

Iterating through the array of objects using the for-of loop and accessing its properties. obj_id 1 obj_value TutorialsPoint obj_id 2 obj_value TypeScript obj_id 3 obj_value Shubham obj_id 4 obj_value TutorialsPoint obj_id 5 obj_value TypeScript

Follow the below steps for next example

  • Step 1 − Create a Tree interface that contains the id, tree_name, and age properties. Also, make the age property optional by using the question mark.
  • Step 2 − Create the array named trees, which can contain the objects of type Tree.
  • Step 3 − Initialize the array with some objects. In the below example, some objects contain age property, and some don’t, as it is optional
  • Step 4 − Use the filter() method of the Array to filter all objects whose age is greater than 20.
  • Step 5 − In the parameter of the filter method, pass the callback function, which takes a particular tree object as a parameter and returns the Boolean value based on whether the tree object contains the age property or not, and if it contains, then its value is greater than 20 or not.
  • Step 6 − Print the filteredTrees array.

Example

In this example, we have implemented the above steps to create the array of Tree objects. Also, we have used the filter() method of the Array library to filter all objects whose age is above 20.

// Creating the interface for the Tree object // age is the optional property interface Tree < id: number; tree_name: string; age?: number; >// creating the array of trees let Trees: Array = [ < id: 10, tree_name: "Palm tree" >, < id: 15, tree_name: "Guava tree", age: 30 >, < id: 20, tree_name: "Papita tree", age: 15 >, < id: 25, tree_name: "Grass tree" >, < id: 35, tree_name: "Neem tree", age: 21 >, ]; // filtering all trees whose age is above 20 years let filteredTrees: Array = Trees.filter((tree) => < return tree.age ? tree.age >20 : false; >); console.log("The all trees whose age is above 20 are"); console.log(filteredTrees);

On compiling, it will generate the following JavaScript code −

// creating the array of trees var Trees = [ < id: 10, tree_name: "Palm tree" >, < id: 15, tree_name: "Guava tree", age: 30 >, < id: 20, tree_name: "Papita tree", age: 15 >, < id: 25, tree_name: "Grass tree" >, < id: 35, tree_name: "Neem tree", age: 21 >, ]; // filtering all trees whose age is above 20 years var filteredTrees = Trees.filter(function (tree) < return tree.age ? tree.age >20 : false; >); console.log("The all trees whose age is above 20 are"); console.log(filteredTrees);

Output

The above code will produce the following output −

All trees whose age is above 20 are

Users learned to create an array of objects. Also, we learned to create objects with optional properties and add them to the array.

Furthermore, we learned to iterate through the objects array using the for-of loop, but users can also use the for or while loop. Also, we learned to use the filter() method with the array of objects, and in such a way, users can also use other methods like find()and sort(). We need to optimize the callback function according to the requirement.

Читайте также:  Эффект плавного появления css

Источник

Typescript new array of objects

TypeScript array of objects:

Array of objects can be defined in TypeScript to store data of a specific type in a sequential way. Similar to string, int or any other array, we can also have an array of objects. It is actually helpful if you are storing data in object-oriented way.

We can create an array of objects in different ways. Let me show you all one by one.

Method 1: Inline initialization of an array of objects:

Let’s take a look at the below example:

let students = [ name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', age: 20 >];

students is an array of objects. We have not defined any type here, but it will take the type implicitely.

let students: name: string, age: number>[] = [ name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', age: 20 >]; console.log(students);

We are printing the content of students on console. It will print the below output:

[  name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', age: 20 > ]

Method 2: Initializing an array of objects with optional properties:

In the above example, name and age are required for each objects. If we don’t have any of them in any object, it will throw one error.

typescript showing error

We can mark any property optional to remove this error.

let students: name: string, age?: number>[] = [ name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', >]; console.log(students);

In this example, the third object doesn’t have age. It will not show any error because we have marked age as optional.

Method 3: Creating an array of objects with an interface:

In typescript, we can also create one array of objects with the type defined by an interface. The interface will hold the structure of each objects and in the array we can initialize it as this type.

interface Student name: string; age?: number; > let students: Student[] = [ name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', >]; console.log(students);

In this example, Student interface holds one name of type string and optional age of type number. We are using the interface instead of the object type defined in previous examples.

Method 4: Creating an array of objects with type alias:

It is almost similar to interfaces. We can use a type alias instead of an interface.

=  name: string; age?: number; > let students: Student[] = [ name: 'Alex', age: 20 >,  name: 'Bob', age: 21 >,  name: 'Charlie', >]; console.log(students);

It will give similar result.

Instead of interfaces, we can also use a class to define objects of that class type.

class Student name: string; age?: number; constructor(n: string, a?: number) this.name = n; this.age = a; > > let students: Student[] = [new Student('Alex', 20), new Student('Bob', 21), new Student('Charlie')]; console.log(students);

Student is a class with two properties similar to the previous interface. We are creating new Student objects and inserting them to the array.

[ Student  name: 'Alex', age: 20 >, Student  name: 'Bob', age: 21 >, Student  name: 'Charlie', age: undefined > ]

Since all are Student class objects, the print output is bit different than the previous example.

We can use all array operations in an array of objects. For example, the below example uses map to iterate over the items and prints the name for each:

class Student name: string; age?: number; constructor(n: string, a?: number) this.name = n; this.age = a; > > let students: Student[] = [new Student('Alex', 20), new Student('Bob', 21), new Student('Charlie')]; students.map(s =>  console.log(s.name); >)

It is an array, so all operations supported by typescript array can be performed.

Источник

How To Define An Array Of Objects In TypeScript?

Tim Mouskhelichvili

Often, a TypeScript developer needs to define an array of objects. Luckily, this is easy to achieve.

In TypeScript, to define an array of objects, you can:

This article will go through those methods and show how to implement them with code examples.

To define an array of objects in TypeScript, a developer must specify the object’s type AND pass it to the array. That way, the array will only be able to hold objects of that specific type.

Solution #1 — Use an existing type or interface

The easiest way to define an array of objects is to define a type or interface that matches the desired structure of one object of the array. Then, you can set the type of the array that holds the objects to array of the created type (or interface).

Let’s see how it works with an example.

typescriptinterface IPerson < name: string; age: number; > const people: IPerson[] = [ < age: 27, name: 'Tim' >, < age: 28, name: 'Bob' > ]

As you can see, we create the IPerson interface, which we use to define the array’s type.

Solution #2 — Use an inline type

If you don’t plan to re-use the object’s type that the array holds, you can define an inline type.

Let’s see how it works with an example.

typescriptconst people: < name: string; age: number; >[] = [ < age: 27, name: 'Tim' >, < age: 28, name: 'Bob' > ]

However, this method can become hard to manage if the object’s type holds a lot of different properties.

The best Web Development course in 2023! 👉 Learn Web Development

Solution #3 — Use the built-in Array type

Another way to define an array of objects in TypeScript is by using the special built-in Array type.

The Array type accepts a generic argument that indicates the structure of the object that the array holds.

Let’s see how it works with an example.

typescriptconst people: Arraystring; age: number; >> = [ < age: 27, name: 'Tim' >, < age: 28, name: 'Bob' > ]

Some developers prefer to use the Array type instead of [] because it is more verbose.

Solution #4 — Use the typeof operator

A different way to define an array of objects involves using the TypeScript typeof operator.

Let’s see how it works with an example.

typescriptconst item1 = < age: 27, name: 'Tim' >; const item2 = < age: 28, name: 'Bob' >; const people: Arraytypeof item2> = [ item1, item2 ];

Using the typeof operator, we can determine the object’s structure and pass it to the Array type.

However, you must have one object constant ready before the array’s initialization.

Final thoughts

As you can see, it is easy to create an array of objects in TypeScript.

We have four different ways of achieving it.

Which one you choose is a question of preference.

typescript array of objects

Here are some other TypeScript tutorials for you to enjoy:

The best Web Development course in 2023! 👉 Learn Web Development

Tim Mouskhelichvili

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.

Источник

Оцените статью