Is there a way to loop through objects in Angular 2

I am working with an Array of Objects named comments, and my goal is to select only the ones that have a specific post id and copy them to another array of objects. The issue I am facing is finding a way to duplicate the object once it has been identified. Below is the function I have implemented:

comments = [];
commentspart = [];
private loadPartComments(id){          
            this.comments.forEach(element => {
            if (element.postId == id) {
                this.commentspart = ????;
                }
            });
            return this.commentspart;
        }

Any assistance would be greatly appreciated.

Answer №1

It seems like you're in search of the filter method.

    comments = [];
commentsSubset = [];
private loadSubsetComments(id){          
            this.commentsSubset = this.comments.filter(item => {
               return item.postId == id;
            });
        }

This will provide you with a subset of comments filtered by the specified id.

I hope this information proves helpful!

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

Encountering issues when implementing any ng statement

Just recently, I completed the installation of node and npm on my Ubuntu system. Along with that, I also installed Angular CLI. However, upon trying to use the ng statement such as ng new test-project, I encountered the following error: ----Mg: -- watch ...

Order Typescript by Segment / Category

Suppose we start with this original array of objects: {vendor:"vendor1", item:"item1", price:1100, rank:0}, {vendor:"vendor1", item:"item2",price:3200, rank:0}, {vendor:"vendor1", item:"item3", price:1100, rank:0}, {vendor:"vendor2", item:"item1", price: ...

What is the proper way to specify the interface as Dispatch<Action>?

My goal is to create an interface with the dispatch function without using Redux. interface DispatchProps { dispatch: (action: { type: string }) => void; } export function addTwoToNumber({ dispatch }: DispatchProps) { dispatch({ type: '@addTwo ...

Tips for creating a responsive swiper slider in an Angular project

In my Angular project, I am using a swiper slider with 4 items in desktop view. However, I would like to display only 1 item in the mobile view. You can see the code at this link: https://stackblitz.com/edit/ngx-swiper-wrapper-demo-h9egdh?file=app/app.com ...

Discovering the JavaScript source file for a package using WebStorm and TypeScript

In my TypeScript project, there is a usage of Express with the following method: response.send('Hello'); I am interested in exploring the implementation of the send() method. However, when I try to navigate to the source code by ctrl+clicking o ...

There is an issue with the hook call while trying to establish a context with a reducer

I am facing an issue while setting up the AppProvider component that utilizes a context and reducer to manage global data for my application. The problem seems to be arising from the useReducer hook used within the AppProvider. I have checked the error mes ...

What could be causing the failure of the subscribe function to interpret the API response

I want to retrieve user information by using their identification number through a method component.ts identificacion:any = this.route.snapshot.paramMap.get('identificacion'); constructor(private route: ActivatedRoute, private dataService: ...

AWS Alert: Mismatch in parameter type and schema type detected (Service: DynamoDb, Status Code: 400)

Upon trying to log into my development Angular system, I encountered the following error. My setup involves AWS Serverless, Amplify Cognito, and Graphql. An error occurred: One or more parameter values were invalid. Condition parameter type does not ma ...

Having trouble accessing a custom factory within a directive in Angular using TypeScript

Having some trouble with my injected storageService. When trying to access it in the link function using this.storageService, I'm getting an undefined error. Any assistance on this issue would be greatly appreciated. module App.Directive { import ...

What is the method for obtaining a literal type through a function parameter to use as a computed property name?

Can you help me with this code snippet? const fn = (name: string) => { return { [name]: "some txt" }; }; const res = fn("books"); // books or any other string The type of res recognized by TS is: const res: { [x: string]: string ...

Generate a fresh array from the existing array and extract various properties to form a child object or sub-array

I am dealing with an array of Responses that contain multiple IDs along with different question answers. Responses = [0:{Id : 1,Name : John, QuestionId :1,Answer :8}, 1:{Id : 1,Name : John, QuestionId :2,Answer :9}, 2:{Id : 1,Name : John, QuestionId :3,An ...

How can I modify the appearance of folders in FileSystemProvider?

I have created an extension for vscode that includes a virtual filesystem with fake directories and files. While the extension is functioning properly, I am facing some challenges in customizing certain aspects due to lack of documentation. 1) I need to u ...

Issue with TypeScript when using destructuring on an object

When attempting to destructure data from an object, I encountered the error message Property XXXX does not exist on type unknown. This issue arose while using React Router to retrieve data. let {decoded, reasonTypes, submissionDetails} = useRouteLoaderDa ...

What is the significance of having both nulls in vue's ref<HTMLButtonElement | null>(null)?

Can you explain the significance of these null values in a vue ref? const submitButton = ref<HTMLButtonElement | null>(null); ...

How does [name] compare to [attr.name]?

Question regarding the [attr.name] and [name], I am utilizing querySelectorAll in my Typescript as shown below: this._document.querySelectorAll("input[name='checkModel-']") However, when I define it in the HTML like this: <input [name]="check ...

Issue: supportsScrollBehavior has been declared as non-configurable

I am attempting to monitor a function called supportsScrollBehavior within the angular platform service using the following code snippet - import * as platform from '@angular/cdk/platform'; describe('Supporting Scroll Behaviour', ( ...

How to access the types of parameters in a function type

I am working on a function that takes a value and default value as arguments. If the value is a boolean, I want the return type to match the type of the default value. Here is the function I have: export type DetermineStyledValue<T> = ( value: str ...

Routing in Angular 2 with .NET Core

I am experiencing an issue with my ASP.NET CORE app that utilizes angular2 routing. When I run the app locally, the routes work as expected. However, once I publish it to the server (running IIS 7), the routes seem to resolve to the server root instead of ...

Error in GraphQL query: specified argument is mandatory, yet not supplied

I recently started learning about graphql and encountered an issue with my query. Here is the code I am using: { product { id } } "message": "Field "product" argument "id" of type "String!" is requir ...

At what point do we employ providers within Angular 2?

In the Angular 2 documentation, they provide examples that also use HTTP for communication. import { HTTP_PROVIDERS } from '@angular/http'; import { HeroService } from './hero.service'; @Component({ selector: 'my-toh&ap ...