Guide to filtering an object by property values within an array using typescript/angular

As I delve into learning TypeScript, one question that arises is the most efficient method for subsetting an object based on the property values from another array.

Consider the following object and array:

const Aobject = 
{
  "cities": [
    {
      "id": "city_id1",
      "name": "NY"
    },
    {
      "id": "city_id2",
      "name": "BOS"
    },
    {
      "id": "city_id3",
      "name": "SF"
    },
    {
      "id": "city_id4",
      "name": "LA"
    }
   ]
}

const Aarray = ["city_id2", "city_id3"]

The expected output in array form would be:

[
  {
    "id": "city_id2",
    "name": "BOS"
  },
  {
    "id": "city_id3",
    "name": "SF"
  }
]

Answer №1

Give this a shot

newResults = [];

filterArray() {
this.sampleObject.locations.forEach(item => {
  this.filterValues.forEach(value => {
    if (item.id.includes(value)) {
      this.newResults.push(item);
    }
  });
});
console.log(this.newResults);
}

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

Updating Time by Adding Minutes using ngFor Loop in Angular 4

I'm currently developing a scheduler that requires user input for start time and the time between two games. I am looking to display the time in a loop using ngFor, incrementing by minutes each time. How can I accomplish this within an Angular 4 HTML ...

Customize stepper background color in Angular Material based on specific conditions

I am working on a project using Angular Material and I want to dynamically change the color of the stepper based on different states. For example: state: OK (should be green) state: REFUSED (should be red) Here is what I have done so far: <mat-horizo ...

'The condition 'NgIf' does not fall under either 'ComponentType' or 'DirectiveType' category

Encountering an error when using *ngIf in a basic component is quite puzzling. This particular issue seems to be triggered by the following code and app.module setup: app.component.html: <ng-container *ngIf="true"> <div>True</di ...

The concept of a singleton design pattern is like a hidden treasure waiting to be

My approach to implementing the singleton pattern in a typescript ( version 2.1.6 ) class is as follows: export class NotificationsViewModel { private _myService: NotificationService; private _myArray: []; private static _instance: Notificatio ...

Disable JavaScript import optimization for a specific file in IntelliJIDEA

I recently came across a tutorial on Angular 2 Google maps that I was following: The tutorial included the following import statement: import { } from 'googlemaps'; However, I encountered a problem where IntelliJ recognized this as an empty im ...

Extracting an array from an HTTP response in Angular/Typescript using the map operator or retrieving a specific element

Q1: How can I extract an array of objects from a http response using map in Angular? Q2: Is there a way to retrieve a specific object from a http response by utilizing map in Angular? Below are the example URL, sample data, CurrencyAPIResponse, and Curre ...

Show the MatCalendar by clicking on a link

Is there a way to trigger the opening of a Material Calendar component using an anchor element? I tried, but the calendar always pops up in the top left corner of the page: <li> <mat-calendar class="hidden"> <input matIn ...

Websocket onmessage event triggered just one time

I have implemented a basic WebSocket client in an Angular 6 application. Everything seems to be working fine, except for the fact that both socket.onmessage and socket.addEventListener('message' are only triggered once. There are no errors in th ...

Receiving an unexpected value from the input attribute

Currently, I am facing a challenge in retrieving data from another component by using the selector in the HTML file of the parent component. Here is how I implemented it: <app-graphs [module]="module" hidden></app-graphs> In the chi ...

There was a DOMException in Angular because the transaction is not active when trying to execute 'getAll' on 'IDBObjectStore'

private get ctxMessage() { const messageTransaction = this.db.transaction('messages', 'readwrite'); const messageStore = messageTransaction.objectStore('messages'); return { messageTransaction, messageStore }; } ...

Encountering "Module ts-jest not found in the transform option" Error During Bazel Testing

In my working Bazel BUILD file, I have set up the following configurations: package(default_visibility = ["//visibility:public"]) load("@io_bazel_rules_docker//nodejs:image.bzl", "nodejs_image") load("@npm_bazel_typescript//:index.bzl", "ts_library") # ...

Encountering an error while attempting to upgrade to Angular 9: Unable to locate the exported node name

Upon upgrading to Angular 9 and attempting to run my project, I encountered the following error: Compiling @angular/common/http : module as esm5 Compiling angular-font-awesome : module as esm5 Compiling angular-font-awesome : module as esm5 Error: Error ...

Is it considered poor practice in TypeScript to manually set the type when the type inference is already accurate?

Is it necessary to explicitly set the variable type in TypeScript when it is inferred correctly? For example: const add = (a: number, b: number) => a + b; const result = add(2, 3); // Or should I explicitly declare the return value type? const add = ...

Importing modules that export other modules in Typescript

I am facing an issue with two modules and two classes. ModuleA, ModuleB, ClassA, and ClassB are defined as follows: export class ClassA { } export class ClassB { } The modules are structured like this: export * from './ClassA'; export module ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...

Error: Unable to locate module: 'fs' in 'node_modulesdotenvlib' - Next.js

I'm currently incorporating dotenv into my React project to use for API_URL. However, when I attempt to implement it in the index.js file within Next.js, I encounter the following error: Module not found: Can't resolve 'fs' in 'nod ...

Configuring .NET Core to send authentication cookies to a separate domain

I am facing an issue with using cookies on the frontend, which has a domain different from the backend. The backend is built with .Net Core and the frontend with Angular. I have learned that I need to set withCredentials: true when making http calls. Howev ...

Error: Unable to initialize i18next as a function

For my current project, I am utilizing TypeScript and i18next for internalization. TypeScript version: 2.1.4 i18next version: 2.3.4 @types/i18next version: 2.3.35 In the specific file: import * as i18next from 'i18next'; i18next.init({ ...

Experiencing template parsing errors in Angular 2+ unit tests with Karma and Jasmine

Encountering problems with running Angular tests on certain components, even though they function properly in production. Seeing the following error message: Failed: Template parse errors: 'app-date-picker' is not a recognized element: 1. Ensure ...

Upgrade your AngularJS Directive to an Angular 2.x+ Directive by using an HTML decorator

Is it no longer possible to utilize Angular directives as what I like to refer to as "HTML decorators"? I found this method extremely useful in Angular 1.x when transitioning legacy applications to Single Page Apps by creating a set of directives to enhan ...