Tips on how to loop through an array in TypeScript to retrieve values from another array

In my ts file, I have defined an array named "myimages" that contains the paths to several images.

myimages: any=[
    {img_path:"assets/img/image1.jpg"},
    {img_path:"assets/img/image2.jpg"},
    {img_path:"assets/img/image3.jpg"},
    {img_path:"assets/img/image4.jpg"},
    {img_path:"assets/img/image5.jpg"},
    {img_path:"assets/img/image6.jpg"},
    {img_path:"assets/img/image7.jpg"},
    {img_path:"assets/img/image8.jpg"},
    {img_path:"assets/img/image9.jpg"},
    {img_path:"assets/img/image10.jpg"}
];


galleryImages = [

    for (let i = 0; i < myimages.length; i++) {    
        small: 'myimages[i]',
        medium: 'myimages[i]',
        big: 'myimages[i]'
    }

];

I am looking to assign the image paths from the "myimages" array into the small, medium and big values within the "galleryImages" array. However, when I tried the above code, I encountered a ts1137 error related to the for loop syntax. As a newcomer to Angular, I am struggling to find a solution. Any help would be greatly appreciated. Thank you in advance.

Answer №1

It's recommended to utilize the map function in place of a traditional for loop.

Make sure to properly declare your variables using const, let, or var before use.

var myImages: any = [
  { img_path: "assets/img/image1.jpg" },
  { img_path: "assets/img/image2.jpg" },
  { img_path: "assets/img/image3.jpg" },
  { img_path: "assets/img/image4.jpg" },
  { img_path: "assets/img/image5.jpg" },
  { img_path: "assets/img/image6.jpg" },
  { img_path: "assets/img/image7.jpg" },
  { img_path: "assets/img/image8.jpg" },
  { img_path: "assets/img/image9.jpg" },
  { img_path: "assets/img/image10.jpg" }
];

var galleryImages: any = myImages.map((image: any) => ({
  small: image,
  medium: image,
  big: image
}))

Answer №2

Discover a simpler way to accomplish it

pictureCollection: any=[
    {img_path:"assets/img/image1.jpg"},
    {img_path:"assets/img/image2.jpg"},
    {img_path:"assets/img/image3.jpg"},
    {img_path:"assets/img/image4.jpg"},
    {img_path:"assets/img/image5.jpg"},
    {img_path:"assets/img/image6.jpg"},
    {img_path:"assets/img/image7.jpg"},
    {img_path:"assets/img/image8.jpg"},
    {img_path:"assets/img/image9.jpg"},
    {img_path:"assets/img/image10.jpg"}
];

const photoGallery: any = pictureCollection.map((img: any) => ({
  small: img,
  medium: img,
  big: img
}));

Answer №3

It's highly recommended to steer clear of using the any type in your code. A cleaner solution could look something like this:

interface Image {
   img_path: string;
};

const myimages: Image[] = [
  { img_path: "assets/img/image1.jpg" },
  { img_path: "assets/img/image2.jpg" },
  { img_path: "assets/img/image3.jpg" },
  { img_path: "assets/img/image4.jpg" },
  { img_path: "assets/img/image5.jpg" },
  { img_path: "assets/img/image6.jpg" },
  { img_path: "assets/img/image7.jpg" },
  { img_path: "assets/img/image8.jpg" },
  { img_path: "assets/img/image9.jpg" },
  { img_path: "assets/img/image10.jpg" }
];

const galleryImages = myimages.map(image => {
  return {
    small: image.img_path,
    medium: image.img_path,
    big: image.img_path
  };
});

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

Issue with Jest mock function failing to trigger axios instance function causing it to return undefined

I initially found a solution on this StackOverflow thread However, I wanted to add my own helper function that generates a fresh Axios instance with the user's authentication token. Here is what I came up with: import axios from "axios"; c ...

How can you generate a distinct id value for each element within an ngFor iteration in Angular 4?

I encountered an issue where I must assign a distinct id value to each data row within my *ngFor loop in angular 4. Here is the code snippet: <div *ngFor="let row of myDataList"> <div id="thisNeedsToBeUnique">{{ row.myValue }}</div> & ...

Error encountered during Typescript compilation: Type 'void' cannot be assigned to type 'Item[]'

Below are my typescript functions. When I edit in vscode, the second function does not show any error message. However, upon compilation, an error is displayed for the second function: error TS2322: Type 'Promise<void>' is not assignable t ...

Looking for giphy link within a v-for loop (Vue.js)

I am fetching a list of movie characters from my backend using axios and rendering them in Bootstrap cards. My objective is to search for the character's name on Giphy and use the obtained URL as the image source for each card. However, when I attemp ...

Encountering an issue where trying to access 'errors' property results in undefined error in Angular 14 validation modifications

Initially, I had a functional code in Angular 12 implemented with a reactive form. When transitioning to Angular 14 for a new project, I researched the updated validation features and adjusted my code accordingly. However, upon testing, I encountered a ser ...

How can we add a key:value pair at a specific position in an array in Angular 2 using Typescript?

Is there a way to insert a key value pair at a specific index in an array? I am currently struggling with this task. Here is the code I have been working on: this.quiz.push( { "question-no":this.no, "Ans":this.ans } I require this functionality to ...

Unable to call a component's method from a different component in Angular 7

How can I call the toggleSidebar() method of the SidebarComponent from the HeaderComponent using the callToggleSidebarOnToggleSidebarBtn() method? I am encountering an error that I cannot comprehend. What is the correct way to use a method of one component ...

After running a yarn build on a TypeScript project using a .projenrc.js file, make sure to include any packaged or additional text files in the lib folder, rather

After utilizing projen to create my typescript project, I followed these steps: mkdir my-project, git init, and npx projen new typescript. Additionally, I created two files - sample.txt and sample.js, along with the default file index.ts within the folder ...

Populating a PrimeNG data grid using an array

I am currently facing a challenge while working with Angular and PrimeNG. I am new to this technology stack and trying to populate a table, but I seem to be missing something as there are no errors in the console. Here is the code snippet that I am struggl ...

Guide for releasing a typescript package compatible with both node and react applications

I have developed an authentication library in TypeScript which I have released on npm. My goal is to make this library compatible for use in both Node.js projects and React projects created with create-react-app. However, I am facing an issue where one of ...

Angular - Tips for effectively positioning a fixed navbar while scrolling to sections sharing the same ID

In my Angular project, I've set up different sections on a page, each with its own unique ID. There's also a fixed-position navbar for easy navigation between these sections. My main objective is to ensure that when a user clicks on a menu item ( ...

There is an issue with the Next.js middleware: [Error: The edge runtime is not compatible with the Node.js 'crypto' module]

Struggling with a problem in next.js and typescript for the past 4 days. If anyone can provide some insight or help with a solution, it would be greatly appreciated. Thank you! -- This is my middleware.ts import jwt from "jsonwebtoken"; import { ...

Are generic constraints leading to type inference selecting the incorrect candidate?

TypeScript Version: 2.6.0-dev.20170826 and 2.4.2 I'm questioning whether I've encountered a TypeScript inference bug or limitation, or if my code is simply incorrect. If the code is valid and it's an issue with type inference, I will repor ...

Creating fixtures with Playwright is a simple process that can greatly enhance

I have a requirement to set up fixtures where the first fixture is always available (acting as a base class) and the second fixture will vary in different test files (like a derived class). I've implemented the following code which seems to be working ...

Removing a dynamic TypeScript object key was successful

In TypeScript, there is a straightforward method to clone an object: const duplicate = {...original} You can also clone and update properties like this: const updatedDuplicate = {...original, property: 'value'} For instance, consider the foll ...

Node_modules folder is excluded from Typescript compilation

I am struggling to understand why TypeScript is not compiling code from the node_modules folder. Below is the content of my tsconfig.json file: { "compilerOptions": { "rootDir": ".", "baseUrl": ".", "paths": { "shared": ["./src/shared ...

Receiving contextual information from Microsoft Teams within an Angular application integrated as a tab

I am currently integrating an Angular website into a Microsoft Teams tab. In order to perform certain computations, I need to retrieve the Team ID. To achieve this, I have recently added npm install --save @microsoft/teams-js. Below is the code snippet th ...

Incorporating traditional Javascript classes for modeling in React development

Can traditional JavaScript classes be utilized in models within the MVC framework while using React, as opposed to relying on Redux or contexts & reducers which may impact reusability? If this approach is feasible, how can we efficiently 'subscribe&ap ...

Adjust the dimensions of the ng2-charts to fit your needs

Is there a way to specify the width and height of a chart using ng2-charts? Specifically, I am working on a Bar chart similar to the one shown in the ng2-charts demo. public doughnutChartLabels:string[] = ['EMI', 'Car', 'Food&apos ...

Is it possible to loop through each row in a table using Cypress and execute the same actions on every iteration?

I have a frontend built with html/typescript that features a table of variable length containing action buttons in one of the columns. I am looking to create a Cypress test that will click on the first button of the first row, carry out a specific task, an ...