Tips for locating elements within an array of objects in JSON

I am working on implementing a search filter for accordion data that should be able to search within the title and contents, including the 'name' key.

Currently, I have a function in place to perform this search, but it does not cover searching within the 'children' key as well.

let filteredTiles = this.tileData.filter((value) => {  //tileData represents the JSON array
    return value.name.toLowerCase().indexOf(searchValue) != -1 ? value : null;
});

Is there a way to modify the search function to include searching within the children of the JSON data?

Check out the Demo on Stackblitz

This is an example of my JSON data:

[
    {
      "name": "First",
      "image": "https://img.freepik.com/free-vector/football-2022-tournament-cup-background_206725-604.jpg?size=626&ext=jpg",
      "children": [
        {
          "name": "Firstone",
          "image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
          "url": "http://www.google.com"
        },
        {
          "name": "Firsttwo",
          "image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
          "url": "http://www.google.com"
        },
        {
          "name": "Firstthree",
          "image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
          "url": "http://www.google.com"
        }
      ]
    },
    {
      "name": "Second",
      "image": "https://media.istockphoto.com/id/517188688/photo/mountain-landscape.jpg?s=612x612&w=0&k=20&c=A63koPKaCyIwQWOTFBRWXj_PwCrR4cEoOw2S9Q7yVl8=",
      "children": [
        {
          "name": "Secondone",
          "image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
          "url": "http://www.google.com"
        },
        {
          "name": "Secondtwo",
          "image": "https://media.istockphoto.com/id/517188688/photo/mountain-landscape.jpg?s=612x612&w=0&k=20&c=A63koPKaCyIwQWOTFBRWXj_PwCrR4cEoOw2S9Q7yVl8=",
          "url": "http://www.google.com"
        },
        {
          "name": "Secondthree",
          "image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
          "url": "http://www.google.com"
        }
      ]
    }

]

Answer №1

This is a method similar to filtering objects within an array.

When using the predicate, you must filter the nested object within the array. If the filtering of a nested array returns an index greater than -1, it indicates that there are nested objects that meet the filter criteria.

Additionally, you can utilize Array.some(predicate), which provides a boolean value as an alternative to

Array.findIndex(predicate) > -1
.

this.tileData.filter((value) => {
  return 
    value.children.some(
      (c) => c.name.toLowerCase().indexOf(searchValue) > -1
    )
  ;
});

If you need to filter whether the root object or nested children meet the filter criteria, you should use the || (or) operator.

let filteredTiles = this.tileData.filter((value) => {
  return (
    value.name.toLowerCase().indexOf(searchValue) > -1 ||
    value.children.some(
      (c) => c.name.toLowerCase().indexOf(searchValue) > -1
    )
  );
});

Check out the demo on StackBlitz

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

How to Convert TXT File into Two-Dimensional String Array using C#

I'm trying to figure out how to convert a text file I have into a 9x7 2D String array. Each Pipe character should create a new column, and each Enter character should create a new row. 100|What color is the sky?|Blue,Red,Green,Orange|Blue Here is the ...

Deserializing a dictionary using the JsonFX library

When attempting to serialize a dictionary of type Dictionary<string, object> that contains a mixture of primitive and complex variable types, such as lists, everything works as expected. However, upon deserializing the JSON string back to a Dictionar ...

When deciding between StoreModule.forRoot and StoreModule.forFeature, consider the specific needs of your application

After researching, I discovered that the .forRoot function merges all reducers, allowing you to manipulate multiple reducers simultaneously when manipulating the state. On the other hand, the .forFeature function gives you the ability to manipulate each r ...

Navigating within the same URL page in Ionic 5

Hey there, I'm trying to set up a routing system where a page can navigate to the same URL but with different parameters. However, it seems like my routing is working fine for other pages but not for navigating to the exact same URL page. Here's ...

Controller using the 'as' syntax fails to add new object to array

Lately, I've been experimenting with the Controller as syntax in Angular. However, I seem to be struggling to grasp its functionality. I am currently following a tutorial that utilizes $scope to bind the members of the controller function rather than ...

Every time I try to upload a file to a folder on the server, the HttpContext.Current.Request.Files.Count is returning null

https://i.sstatic.net/MAnjz.png I have received this request payload. fileChange(event) { debugger; let fileList: FileList = event.target.files; if (fileList.length > 0) { let file: File = fileList[0]; let formData: FormData = new FormData(); fo ...

*ngIf doesn't actually remove the element if the condition is False; rather, it generates a new one when the condition

As I venture into the world of Angular, I encountered a snag with *ngIf Upon launching the app, *ngIf="item.done" works correctly in showing or hiding the element based on whether the ToDo item is marked as done. However, upon clicking on the element, des ...

Decoding HTTP JSON Response in C#

I'm currently working on incorporating OAUTH2 login functionality into a Winforms application. Upon sending credentials to the server, I receive a response containing a token in JSON format. What would be the most effective way to extract and utiliz ...

Traverse JSON data with JavaScript/jQuery

I am looking to iterate through the JSON data provided below using JavaScript. { "jsonUrl": "/testUrl", "data": { "country":"US", "company":"ABC", "items":[ { "id": "1", "i ...

What is the best way to include a 'parent node' in a JSON document?

I have created a SQL query using CTEs that returns 6 products along with their attributes. The query is simply select * from output which generates a table with more columns than displayed below: |row | gender | prod_1| url_1 | prod_2 | url_2| ... | 1 | ...

Utilize the power of Request.JSON to send an HTML array as a post

I have a piece of HTML code that includes form elements: First name: <input type='text' name='first_name' value='' /><br/> Last name: <input type='text' name='last_name' value='' / ...

Display a Component in React that is similar to the one currently being rendered

Creating a feature in my React project where clicking on a card component (Card.js) opens another component (Suggestion.js) with matching IDs. Need help implementing the code for handling this functionality. Thank you! App.js // App component code here.. ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...

Issue with PHP incorrectly encoding JSON when writing to a file

I encountered a problem while working on this task. I used preg_split in PHP to create an array. However, my challenge now is converting it into JSON format. Despite trying several methods, the resulting code appears poorly written and does not seem to be ...

Issue with asynchronous Validator when used in conjunction with mat-autocomplete

When implementing the validate function, I make a request to the API to verify if the data is valid, which works smoothly. However, when the value is an object, I simply return null, but this causes the mat-autocomplete panel to never close. import { Chan ...

Manipulating Arrays and Loop Iteration, Issues with Using Sentinels in C Programming

I tried implementing (-999) in this code but it's giving me trouble. I attempted using it with an if/break statement and a while loop, but it doesn't seem to be working properly. Can anyone provide assistance? Create a basic program (to showcase ...

Getting a reply from a jsp page with $http.get in AngularJS: Step-by-step guide

I'm a newcomer to JSON and the $http service in AngularJS. I'm attempting to receive a response from a jsp file located in the same folder. However, when I run it on the server, nothing is being printed, and there are no errors. If anyone could ...

Is it possible to combine file and form data into a single API request in Angular 4 when uploading?

admin.component.ts admin.component.html Here is a snippet of the code used for uploading form data. Although I am able to post the form data to the API, I am facing difficulties with uploading the file. admin.component.ts private onFileChange(event: an ...

The initial update of the view does not occur when a component property changes in Angular 2 RC6

I am currently facing an issue with a component in my project. This component calls a service to retrieve locally stored JSON data, which is then mapped to an array of objects and displayed in the component view. The problem I am encountering is that the v ...

When sending JSON to API Controller, the C# model does not get bound

After searching through numerous posts, I can't figure out what mistake I've made. It seems like there's a minor issue that I just can't spot. Any guidance in the right direction would be greatly appreciated. I have an API controller s ...