Objects
Angular Best Practices Javascript Patterns Typescript

How to Remove and Amend Objects with TypeScript

Welcome to today’s post.

In today’s post I will demonstrate the various ways in which we can remove an object or amend an object from within an array within TypeScript.

Arrays are a very common type that is used within TypeScript to store, retrieve, and manipulate data within an application. I will be covering some useful operations that we can use to filter, modify, and amend objects within an array.

In the first section, I will explain what a TypeScript object is.

What is an Object in TypeScript?

I will explain what an object is in TypeScript. The same definition applies in JavaScript, as TypeScript is a superset of JavaScript.

A plain object in typescript is a JSON object that is declared between parentheses like so:

{ .. }

Within the JSON object, there are key and value pairs like so:

{
	“key1”: value1,
	…
	“keyN”: valueN,
}

Where:

“key1” … “keyN” are strings identifying the keys

value1 … valueN are primitive types (integer, string, number,

In TypeScript, we can declare a plain JSON object as shown:

const mySalaryObject: any = { 
  name: “Andrew”, 
  pay: 500 
};

We can also create a class structure type for the object as shown:

export class EmployeeSalary
{
  public name: string;
  public pay: number;
}

Like we do within many object-orientated languages like C#, a class can also include a constructor and methods. The purpose of this post is to focus on the properties of an object so I will not explain constructors or methods.

Now we can redeclare the same object with the above class type:

const employeeSalaryObject: EmployeeSalary = { 
  name: “Andrew”, 
  pay: 500 
};

An array of objects is enclosed by brackets:

[ … ]

Within the brackets we place each of our objects as shown:

[
  Obj1,
  Obj2,
  …
  ObjN
]

Where Obj1, … ObjN are JSON objects.

We can declare an array of JSON objects as follows:

let employeeSalaryObjectList: EmployeeSalary[] = 
[
  { 
    name: “Andrew”, 
    pay: 505.388 
  },
  { 
    name: “Sally”, 
    pay: 455.667 
  },
  { 
    name: “Peter”, 
    pay: 620.736 
  }
]                 

In the next section, I will show how to remove objects from an array with a filter.

Object Removal from an Array with TypeScript Filter

To demonstrate object removal I will make use of the TypeScript filter() function:

filter(predicate: (value: T, index: number, array: T[]) => 
unknown, thisArg?: any): T[];   

The filter function takes a predicate, which is a condition that acts on each element of the source object. The output is an array of objects that are a subset of the original object array.

For the above array, suppose I want to filter out employees with pay less then $500.

We use the predicate as follows:

e => e.pay < 500

The above returns an object list of employees with pay less than $500 we do this as shown:

let employeesWithPayUnder500: EmployeeSalary[] = 
  employeeSalaryObjectList
    .filter(x => x['pay] > 500);

The above will return a copy object, employeesWithPayUnder500 of the original object list employeeSalaryObjectList, but it will not reduce to size of the original list.

To reduce the size of the original list to the filtered list we can assign the original list back to the filtered list as shown:

employeeSalaryObjectList = employeeSalaryObjectList
  .filter(x => x['pay] > 500);

The above does the following:

  1. Create a new object array containing the filtered object array.
  2. Assign the original object array to a reference to the new object array.

The filtered object array will then consist of the following objects:

[
  { 
    name: “Andrew”, 
    pay: 505.388 
  },
  { 
    name: “Peter”, 
    pay: 620.736 
  }
]

Next, I will show how to amend an object.

Modifying Object Key Values

I will now show how to modify values within a JSON object key value pair.

For the basic scenario, where we are modifying a single object’s value for the pay key:

const employeeSalaryObject: EmployeeSalary = { 
  name: “Andrew”, 
  pay: 500 
};

This can be done in one of two ways:

employeeSalaryObject.pay = 600;

or

employeeSalaryObject[‘pay’] = 600;

Now, should we wish to modify object key values within an array, we can either iterate with the TypeScript forEach() iterator or use the map() function.

We use the forEach() iterator to iterate through each object, then round up the pay using the toFixed() functions:

employeeSalaryObjectList.forEach((element: any) => {
  console.log('monthly pay before = ' + element['pay']);

  let num: number = parseFloat(element[pay']);
    element['pay'] = num.toFixed(2);

  console.log('monthly pay after = ' + element['pay']);
});

As we iterated through each object, we assigned the value for the pay key to a different value.

Again, each element in the lambda is a reference to each object within the object array.

Another alternative is to use the map() function.

map<U>(callbackfn: (value: T, index: number, array: T[]) => 
U, thisArg?: any): U[]; 

Like the filter function, we can apply a lambda that performs an action for each element. Unlike the filter function, a map does not have a filter predicate. The following will achieve the goal of modifying object key values:

this.objectList.map((element: any) => 
{
  console.log('monthly pay before = ' + element['pay']);
  let num: number = parseFloat(element['pay']);
  element['pay'] = num + 100;
  console.log('monthly pay after = ' + element['pay']);
  return element;
});

The above is also equivalent to the assigning and mapping pattern:

this.objectList = this.objectList.map((element: any) => { … }

Assigning and mapping in the above would make sense if the new object array being assigned to is a different object array with a different number of objects. That is:

let anotherObjectList: any[] = this.objectList.map((element: any) => { … }

If we want to reduce the number of objects, then we would have to assign the filtered object array back to either the same object we have filtered, or a different object array. The following filter and mapping pattern will allow us to amend property values of filtered object array element, but not the size (length) of the array of objects:

this.objectList.filter(…).map((element: any) => { … }

The following assignment, filter and mapping pattern will modify the objects and amend the length of the object array:

this.objectList = this.objectList.filter(…).map((element: any) => { … }

In the script below, we apply the above pattern to achieve all the goals of internal object modification and array size:

this.objectList = this.objectList
  .filter(x => x['pay'] !== null)
  .map((element: any) => 
{
  console.log('monthly pay before = ' + element['pay']);
  let num: number = parseFloat(element['pay']);
  element['pay'] = num + 100;
  console.log('monthly pay after = ' + element['pay']);
  return element;
});

Note: Without the return of each element within the delegate handler block, we would be assigning null values to the object on the left side of the assignment.

With the above patterns that have been employed, be aware that TypeScript objects are mutable, which means that object key values can be modified from a reference to a filter or map function.

In addition, being aware that an assignment to another object within TypeScript does not create a copy of the modified object, which is only possible with an immutable type/object, we were then able to apply object modifications and object size reductions quite easily utilizing mutability of JSON objects.

That is all for today’s post.

I hope you have found this post useful and informative.

Social media & sharing icons powered by UltimatelySocial