Loop through an array of objects using Typescript

Currently, I am facing a challenge in Angular 2 where I have an array of objects that I need to iterate over. However, I also need to limit the display length of a specific key's string value within each object.

this.productService.loadAllProducts(product).subscribe(data => {
      if (this.authService.checkActiveSession(data)) {
        if (data.success) {
         //console.log(this.product_desc.substring(0,2))
             for(let i=0;i<data.products.length ;i++){  //I'm struggling with iterating properly here!!
             console.log(data.products[0].product_desc)
          }
          this.source.load(data.products);
         } else {
          console.log('Not binded');
        }
      }
    });
  } 

To achieve this, I've attempted to limit the length of the product description to 10 characters by using:

For example:

this.product_desc.substring(0,10)

Answer №1

To manipulate arrays, you have the option of utilizing the forEach function that comes pre-installed.

See an example below:

// Reduce all product descriptions to a maximum length of 10 characters
data.products.forEach( (item) => {
    item.product_desc = item.product_desc.substring(0,10);
});

Your approach was not incorrect. It could be enhanced as follows:

for(let index=0; index<data.products.length; index++){
    console.log(data.products[index].product_desc); // Use 'index' instead of '0'
}

Answer №2

If you're working with Typescript and ES6, you have the option to utilize for..of:

for (let item of items) {
    console.log(item.item_name);
}

This code snippet will be converted to JavaScript as:

for (let _i = 0, items_1 = items; _i < items_1.length; _i++) {
    let item = items_1[_i];
    console.log(item.item_name);
}

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

What is the best way to transform a ternary operation into an Enum Map with custom properties

I'm faced with the challenge of styling a button based on the selection made in a select box. The code snippet I have currently is as follows: const buttonStyles = { backgroundColor: buttonStyle === 'Black' ? colors.interactiveForeground ...

Utilizing Vue.js to retrieve database information and populate input fields through select options

In my Laravel 8 and Vue 3 application, I have a Student Component with a datalist that lists all the students. My goal is to populate the input fields with the specific student information when clicking on a student. I attempted to use Vue select, which i ...

Creating arrays in JavaScript with or without the use of jQuery

In my JavaScript script, I am defining this array: var status=[ { "name":"name1", "level":0 }, { "name":"name2", "level":0 }, { "name":"name3", "level":0 }, { "name":" ...

Having trouble clicking or interacting with JavaScript using Selenium and Python

Issue: Unable to interact with elements on a specific webpage after opening a new tab. Using WebDriver Chrome. I can successfully navigate the initial webpage until I click a link that opens a new tab, at which point I am unable to perform any actions. ...

Make an AJAX GET call to an ASP.NET Web API endpoint

Here is the ajax script I am using: $.ajax({ dataType: 'json', url: url, data: tuDispId, type: "GET", success: function (data) { bindData(data); $("#ale ...

Is there a way for me to understand the connection between `FormsModule` and `ngModel`?

After following the tutorial on angular hero editor, I came across a puzzling issue regarding FormsModule. It seems that the demo does not function properly without importing FormsModule first: https://angular.io/tutorial/toh-pt1#the-missing-formsmodule ...

Puppeteer: implementing wait timeout is crucial to successfully handle Auth0 login process

Recently, I started using puppeteer and encountered some unexpected behavior. It seems that the waitForSelector function does not work properly unless I include a delay before it. Take a look at the following code: const browser = await puppeteer.l ...

Issues with Node JS app's handling of php mailer code

I've made a basic website using the Node JS framework and included a php mailer for handling the contact form. Unfortunately, I'm facing issues getting it to function properly. Could it be possible that there is an underlying problem with Node JS ...

Sending JSON data parsed by oboe.js to the http response object in a Node.js server

Using Oboe.js for JSON parsing from a Node readStream with the aim of sending it back to the requesting client in a memory-efficient manner. I'm exploring the possibility of piping data from Oboe's node or path events to a Node.js HTTP response o ...

Tips for adjusting the search bar's position on a mobile device when it is activated by the user

I need help with an open source project where I am developing a search engine using Angular. When using smaller screen sizes, the search bar is positioned in the middle but gets hidden behind the keyboard terminal when clicked on. Can anyone advise on ho ...

Issue in CakePHP after modifying the directory of Index

I'm currently working on a project using CakePHP and have come across an issue. Our team developed an Ajax function that sends data to a PHP function responsible for adding a folder (known as "ordner" in German) to the database. Initially, everything ...

Unleashing the power of promises through chaining resolution and rejection

My function returns a deferred.promise, following jQuery's deferred concept. Regardless of the success of the file read, I want to move on to the next step in the chain. Here's an example of how I currently handle it: var a, b, c; readF ...

How to dynamically generate <select> <option> elements in VueJS using the v-for directive

Just started exploring VueJS and I recently learned how to use a v-for loop to populate a Select Options box. <select> <option v-for="person in persons" :value="personid">{{ personname }}</option> </select> ...

Replacing a function in TypeScript

Looking to alter the behavior of the alert function in TypeScript? You can achieve this by creating a new function that wraps around the original alert and modifies its behavior. alert = (function (origAlert) { return function (...messages: any[]) { ...

When using Jest, it is not possible to match 'undefined' using 'expect.any(Object)' or 'expect.anything()'

Looking to test the following module. import * as apiUtils from './apiUtils'; export function awardPoints(pointsAwarding) { return apiUtils.callApiService("POST", "points", pointsAwarding); } This is the test in question. it("should call ap ...

Guide on utilizing AngularJS Filter service without HTML for Chrome extension development

Currently, I am attempting to utilize the filter service in AngularJS within my Chrome extension. However, I am unsure of how to properly obtain and inject it into my function. At this time, my code looks like: chrome.contextMenus.onClicked.addListener(fu ...

Guide on creating a repeating displacement map in three.js

When working with a three.js rendering, I have a small texture that I need to repeat multiple times. This texture includes various maps such as the map itself, a displacement map, a normal map, an ambient occlusion map, and a specular map. Everything looks ...

Updating a field in Mongoose by referencing an item from another field that is an array

I have developed an innovative Expense Tracker Application, where users can conveniently manage their expenses through a User Collection containing fields such as Name, Amount, Expenses Array, Incomes Array, and more. The application's database is p ...

Utilizing elapsed time in coding to create a function for DOM manipulation

As a new software engineering student, I am facing a challenge that I am struggling to overcome. I am currently working on developing a basic rhythm game similar to Guitar Hero using HTML, CSS, and JavaScript. I have successfully implemented an elapsedTim ...

What is the process for modifying the popups associated with a polygon object?

As of now, every time I click on the map, a popup shows up with the name of the country based on a geoJSON file containing multi-polygon lnglat coordinates that outline the borders of each country. This method saves me from manually inputting each country& ...