Guide to sorting through an array for a particular keyword

In my array, I have objects with IDs and names. For example:

{
 [
  {
    "id": 1,
    "name": "this is book",
  },
  {
    "id": 2,
    "name": "this is a test book",
  },
  {
    "id": 3,
    "name": "this is a desk",
  }
 ]
}

Now, let's say I want to filter and return an array that contains the word book

I attempted the following but was unsuccessful -

let test = this.pro.filter((s: { name: any; })=>s.name===book); 

I also tried this but it only returned the first matching result instead of all matching results -

let test = this.pro.filter((s: { name: any; })=>s.name==="this is book"); 

Can anyone provide a solution that returns an array with all items that meet the filter condition/s?

Answer №1

This code snippet is designed to meet your expectations. It searches for the word 'Book' within an array of objects and returns the specific object that contains it.

const products = [
  {
    "id": 1,
    "name": "this is book",
  },
  {
    "id": 2,
    "name": "this is a test book",
  },
  {
    "id"": 3,
    "name": "this is a desk",
  }]

let newArr = products.filter(item=>{
  if(item.name.indexOf('book') > -1){
    return item;
  }
})
console.log(newArr);

Answer №2

Give this a shot:

const filteredBooks = books.filter((book) => book.title.includes('book'));

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

Unable to send JSON data from server to client following a successful file upload operation

I'm currently working on a project that involves NodeJS, Express, JQuery, and Typescript. The issue I'm facing is related to uploading a file from the front end, which is successful. However, I'm encountering difficulties in returning a JSON ...

Enhance Your SVG Elements with Angular Tooltips

I am faced with a challenge on my website where I have an SVG element: <ellipse id="svg_2" cy="78.999999" cx="1042.499999" stroke-width="1.5" stroke="#000" fill="#fff"/> My goal is to add a tooltip to this specific element. I attempted using NGPrim ...

Accessing element from view within controller in Ionic version 3.5

I am currently working on a project in Ionic 3.5, where I need to implement a feature that automatically loads an image "ad" after the page finishes loading. Right now, clicking a button successfully displays the image. However, I want this functionality ...

primeng allows for implementing a table filter functionality with a dropdown selection

I am working with a p-table from primeng and attempting to synchronize the selection from the dropdown menu with the filter method of the table, but I have not been successful in achieving this. Could you please help me identify the issue? <p-table ...

Using Object.defineProperty in a constructor has no effect

I recently revamped my three.js project and ran into a peculiar issue where all objects were being rendered with the same geometry and material. Upon further investigation in the debugger, I narrowed down the problem to this constructor: function Geometry ...

"Enhance Your Text Fields with Angular2 Text Masks for Added Text Formatting

Is there a way to combine text and numbers in my mask? This is what I am currently using: [/\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] The above code only allows for numbers. How can I modify it to allow f ...

Customize validation timing in Angular Reactive Forms

One common query about the conditional validator is understanding when exactly it gets triggered. Imagine a simple form with just two fields this.form = formBuilder.group({ emailRequired: [false], emailRecipients: [''] }); Now, let's s ...

The inRequestScope feature seems to be malfunctioning and is not functioning as intended

Need help with using inRequestScope in inversifyJS For example: container.bind<ITransactionManager>(Types.MysqlTransactionManager).to(MysqlTransactionManager).inRequestScope() ... container.get<ITransactionManager>(Types.MysqlTransactionMana ...

Angular Recurring Request

Currently, I am using Angular5 and making requests every 5 seconds to check the status of a task. However, I would like to implement a more flexible condition where if the request receives a status code of 202, continue sending requests, but if it receives ...

Creating a Jest TypeScript mock for Axios

Within a class, I have the following method: import axios from 'axios' public async getData() { const resp = await axios.get(Endpoints.DATA.URL) return resp.data } My aim is to create a Jest test that performs the following actions: jes ...

How to determine the number of rows in Ag-Grid using Angular

After I input data, the table initially shows 0 rows and 0 selections. However, if I select one row, suddenly 4 rows and 1 selection appear. It's puzzling why the row count is inaccurate when the application loads. onGridReady(params) { this.grid ...

Does Angular 4 Bundling Include the Complete Angular Library in the Bundle?

Is it possible that when running ng build --prod in CMD, Angular gathers all JavaScript files from node_modules and generates the vendor.bundle.js? To test this theory, I decided to delete certain definitions from package.json and rebuild. Surprisingly, t ...

Is there a way to specify the sequence in which Observables are subscribed to in Angular?

Working with API calls in a service.ts file has brought me some challenges. Here is the code snippet: //code getCars() { this.car = this.http.get(car_url) return this.car; } getTires() { this.tires = this.http.get(tires_url) return this.tires; } getSeat ...

The observed function remains untouched

In my code, I have an if condition inside a function that looks like this: public setOption() { setTimeout(() => { if (this.isCMode && !this.quest['isCompleted']) { this.toggleOption(false); } },window['TIME ...

Error in Angular multiselect dropdown: Unable to retrieve the length of undefined property

counter: number = 0; getDatatypes(){ if(this.counter == 0) { if(this.appId != 0) { if(undefined != this.datatypes && this.datatypes.length) for (let i = 0; i < this.datatypes.length; i++) { this.ap ...

Angular project service file experiencing issues with TypeScript string interpolation functionality

Here is the code snippet for a service in an Angular project: @Injectable() export class FetchDataService { fetch(link){ console.log('This is a ${link}'); } } In my component, I am invoking this method with a string parameter. Upon che ...

What is the most efficient method for defining a string structure in TypeScript?

Consider the following example of a JavaScript object: const myObject = { id: 'my_id', // Base value which sets the structure for the following values (always pascal case). upperID: 'MY_ID', // Uppercase version of `id`. camel ...

Tslint is notifying that JSX elements without any children must be self-closing to prevent errors [Error]

Recently, I encountered an issue while trying to build my solution using the command npm run build. The error message displayed was: JSX elements with no children must be self-closing. I came across a similar problem on Stack Overflow but unfortunately ...

Is it possible to select a tab in Angular 10 Material Tabs based on a route parameter?

My webpage features a mat-tab-group, located at the URL /transactions. <mat-tab-group> <mat-tab label="Shipments"> <ng-template matTabContent> shipment content </ng-template> ...

API rest data retrieval service in Angular

I'm currently working on my first Angular App and I need to fetch data from another local API Rest. My project is inspired by the Angular tutorial tour-of-heroes. I have created a component service to make API calls and display the results in another ...