Transform information into a different format and showcase it in a table

Hey there, currently I am working with Typescript on Angular 9. I have a dataset that is structured like the example below and I need to present it in a mat-table.

Is there a way to transform it as follows?

0: CustomPoDTO {id: "1", equipmentOrdered: "Monitor, Keyboard", quantity: 2}
1: CustomPoDTO {id: "2", equipmentOrdered: "Keyboard, Monitor, Mouse", quantity: 6}
2: CustomPoDTO {id: "3", equipmentOrdered: "Mouse", quantity: 2}

to look like this?

0: CustomPoDTO {id: "1", equipmentOrdered: "Monitor and 1 more", quantity: 2}
1: CustomPoDTO {id: "2", equipmentOrdered: "Keyboard and 2 more", quantity: 6}
2: CustomPoDTO {id: "3", equipmentOrdered: "Mouse", quantity: 2}

Answer №1

To effectively showcase information based on the provided data, consider utilizing the equipmentOrdered column and formatting it with a Pipe instead of directly altering the data itself.

<ng-container matColumnDef="equipmentOrdered">
  <th mat-header-cell *matHeaderCellDef>Ordered Equipment</th>
  <td mat-cell *matCellDef="let item">{{ item.equipmentOrdered | displayMore }} </td>
</ng-container>
@Pipe({name: 'displayMore '})
export class DisplayMorePipe implements PipeTransform {
  transform(value: string): string {
    const [firstItem, ...others] = value.split(',');
    return others.length > 0 ? `${firstItem} and ${others.length} more` : firstItem;
  }
}

Answer №2

Simply tally the total number of equipment items ordered

const equipmentOrders = [{id: "1", equipmentOrdered: "Monitor, Keyboard", quantity: 2},
            {id: "2", equipmentOrdered: "Keyboard, Monitor, Mouse", quantity: 6},
            {id: "3", equipmentOrdered: "Mouse", quantity: 2}]

equipmentOrders.forEach((order) => {
   splitEquipment = order['equipmentOrdered'].split(',')
   if (splitEquipment.length > 1) {
     order['equipmentOrdered'] = `${splitEquipment[0].trim()} and ${(splitEquipment.length - 1)} more`
   }
   
})

console.log(equipmentOrders);

Answer №3

To achieve the expected result, follow these instructions:

  Iterate through each element in the array using the forEach method:
   array.forEach(element => {
   Extract the elements in the 'equipmentOrdered' property by splitting the string at the comma:
   const tempString = element.equipmentOrdered.split(',');

   Save the first element from the split string:
   let stringFormation = tempString[0];

   Check if there are more than one element in the split array:
   if(tempString.length > 1) {
   If there are more elements, update the 'stringFormation' variable to include ' and (number of elements - 1) more':
   stringFormation = stringFormation + ' and ' + String(tempString.length-1) + ' more';
  }
  Update the 'equipmentOrdered' property of the element with the modified string:
  element.equipmentOrdered = stringFormation;
});

Answer №4

const purchases = [
    {id: "1", itemsPurchased: "T-shirt, Jeans", quantity: 3},
    {id: "2", itemsPurchased: "Jeans, Shoes, Socks", quantity: 2},
    {id: "3", itemsPurchased: "Socks", quantity: 1}
];

purchases.forEach(purchase => {
    if(purchase.itemsPurchased.includes(',')){
        quantity = purchase.quantity -1;
        purchase.itemsPurchased = purchase.itemsPurchased.split(',').shift() + ' and ' + quantity+ ' more';
    }
});

console.log(purchases)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

TypeScript: implementing function overloading in an interface by extending another interface

I'm currently developing a Capacitor plugin and I'm in the process of defining possible event listeners for it. Previously, all the possible event listeners were included in one large interface within the same file: export interface Plugin { ...

The data type 'number' cannot be assigned to the data type 'undefined'. Error code: ts(2322)

I encountered an issue where it's giving me an error stating that type number cannot be assigned to type undefined on the last digit (1) in scale={[1.618, 1, 1]}. Can anyone help me figure out how to resolve this TypeScript error? "use client&quo ...

Arranging information by utilizing arrays

I am working on a component called components.ts in my Angular project. My goal is to create a function that sorts an array based on counts, and then utilize the sorted data in my HTML to generate a chart. import { Component } from '@angular/core&apo ...

Issue with Ion-Searchbar visibility on Android device

My Angular (Ionic) app runs smoothly on the browser with no issues, using Angular v17.0.2 and Ionic v8.2.2. However, when I use npx cap sync and test it on a device with Android Studio, the layout looks distorted as shown in the second image I attached. I ...

Angular 2 Material Primary Focus

Struggling with altering the foreground color in Angular 2 material? Specifically, the text in the toolbar displays as black. I attempted to adjust it using the following styles: @import '~@angular/material/theming'; $primary: mat-palette($mat- ...

modify style when not valid and is touched

When I try to modify the style of an i tag based on the touched and invalid state of another field, only the input tag's style changes and not the i tag. Here's the CSS code I'm using: input.ng-touched.ng-invalid { border-color: red; } ...

Updating a global variable in Ionic 3

I recently started exploring the world of Ionic, Angular, and TypeScript. I encountered a scenario where I needed to have a variable "ar: AR" accessible across all pages. To achieve this, I decided to make it a global variable by following these steps: Fi ...

Using Angular's asterisk wildcard to correctly match nested routes

Struggling to locate subroutes using a component const routes: Routes = [ { path: '', component: CatalogueComponent, }, { path: 'search/**', component: CatalogueComponent, }, ... { path: '**', ...

Having issues with NGXS subscription not functioning properly when selecting a variable

Currently, I am working with Angular 11 and NGXS. One issue I am facing involves a subscription for a variable in the state. Here is the problematic subscription: @Select(state => state.alert.alerts) alerts$: Observable<any[]> ngOnInit(): void { t ...

Introducing the latest Angular quickstart seed, now with updated dependencies to avoid npm warnings such as the deprecated [email protected

Embarking on my journey with node.js, npm, and Angular has been quite the learning curve. I am currently in the process of setting up a new Angular 2 project using their provided quickstart seed. I'm diligently following the instructions for local de ...

Ways to address the error in typescript: "Namespace 'fastify' not found"?

Recently, I made the decision to update all of the packages on my fastify-server template. Upon inspection, my package.json file appears as follows: { "name": "backend-template", "version": "1.0.0", &quo ...

Event emitters from Angular 4 are failing to receive emitted events after the page is refreshed

Hey there, I'm facing an unusual issue with event emitters not functioning correctly during page refreshes. Here's the scenario: First, the user lands on the login page. Upon successful login, they are directed to the home page where I need spec ...

A comprehensive guide on implementing form array validations in Angular 8

I am currently using the formArray feature to dynamically display data in a table, which is working perfectly. However, I am facing difficulty in applying the required field validation for this table. My goal is to validate the table so that no null entry ...

Protected HTTP Live Streaming 128-bit AES encryption key location

After encrypting a video using HLS AES-128 with the apple tool, I have generated an m3u8 file that looks like this: #EXTM3U #EXT-X-TARGETDURATION:10 #EXT-X-MEDIA-SEQUENCE:0 #EXT-X-PLAYLIST-TYPE:VOD #EXT-X-KEY:METHOD=AES-128,URI="https://xxxxx.com/api/ ...

Cultural adaptation in Angular

I have successfully created an Angular project with internationalization capabilities. However, I am now looking to implement it by culture, such as es-AR or en-NZ. Below are my configurations for Spanish and English in the angular.js file: "build": { ...

What is the best way to assign the value of "this" to a variable within a component using Angular 2 and TypeScript?

In my component, I have the following setup: constructor() { this.something = "Hello"; } document.addEventListener('click', doSomething()); function doSomething(e) { console.log(this.something) // this is undefined } I am struggling to a ...

Dynamic user input using an enumeration

I am looking to develop a flexible input component (in React) that can dynamically generate different types of inputs based on the enum type provided along with relevant inputProps. The idea is to switch between different input components based on the type ...

Removing Firebase Users using Angular2/Ionic2

I'm currently working with Ionic2/Angular2 and I've been searching for a guide on deleting users from Firebase. If anyone has any useful examples, I would greatly appreciate the assistance. Thank you. ...

Utilize Dinero.js to implement currency formatting for input fields in React applications

I am currently working on a form in React that requires certain input fields to be formatted as money currency. These inputs should be prefixed with the dollar sign ($), include commas for thousands separation, and have exactly two decimal points. During ...

typescript Can you explain the significance of square brackets in an interface?

I came across this code snippet in vue at the following GitHub link declare const RefSymbol: unique symbol export declare const RawSymbol: unique symbol export interface Ref<T = any> { value: T [RefSymbol]: true } Can someone explain what Re ...