Guidelines for iterating through a nested JSON array and extracting a search query in Angular

I'm currently working with a complex nested JSON Array and I need to filter it (based on the name property) according to what the user enters in an input tag, displaying the results as an autocomplete. I've started developing a basic version of this on Stackblitz - check out the code here. There are two entries for the name "Tom" in two separate objects, so when a user types "Tom", it should appear twice in the autocomplete instead of just once. Ideally, when the user types the letter "T", all names starting with "T" should be displayed. For example, typing "To" should show "Tom" twice, while typing just "T" should display "Tiffany" and "Tom" both 2 times. Can anyone provide some guidance on how to achieve this in the code? Your assistance is greatly appreciated. Thank you!

Answer №1

If you want to review the updated code as well, feel free to check it out on stackbliz here

matches = [];
  ngOnInit() {}
  searchKeyup(ev) {
 
    var term: any = ev.target as HTMLElement;
    console.log("Value", term.value);
    this.matches = [];
    let content = [
      {
        name: 'Robert',
        children: [],
      },
      {
        name: 'Doug',
        children: [
          {
            name: 'James',
            children: [
              {
                name: 'John',
                children: [
                  {
                    name: 'Tom',
                    children: [],
                  },
                ],
              },
            ],
          },
        ],
      },
      {
        name: 'Susan',
        children: [
          {
            name: 'Tiffany',
            children: [
              {
                name: 'Merry',
                children: [
                  {
                    name: 'Sasha',
                    children: [],
                  },
                  {
                    name: 'Tommy',
                    children: [],
                  },
                ],
              },
            ],
          },
        ],
      },
    ];
    if(term.value.length > 0){
      this.filter(content, term.value);
    } else {
      document.getElementById('list').innerHTML = '';
    }

    if (this.matches.length > 0) {
      document.getElementById('list').innerHTML = this.matches.map(match => match.name).join(",");
    } else{
      document.getElementById('list').innerHTML = "";
    }
    
  }
  filter(arr, term) {
       
    arr.forEach((i) => {
      if (i.name.includes(term)) {
        this.matches.push(i);
      } 
      if (i.children.length > 0) {
        this.filter(i.children, term);
      }
    });
    console.log(this.matches);
  }

Answer №2

It seemed like you were on the right track with your recursive walk. However, one thing that was missing was keeping track of the state of matches throughout the process:

filter(arr, term, matches) {
    if (term.length == 0) {
      matches = [];
      document.getElementById('list').innerHTML = '';
    }
    arr.forEach((i) => {
      if (i.name.includes(term)) {
        matches.push(i);
      } 
      if (i.children.length > 0) {
        this.filter(i.children, term, matches);
      }
    });
    console.log(matches);

    if (matches.length > 0) {
      document.getElementById('list').innerHTML = matches[0].name;
    }
}

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

Enforce boundaries by constraining the marker within a specified polygon on a leaflet map

Currently, I am utilizing a leaflet map to track the user's location. The map includes a marker for the user and a polygon shape. My goal is to ensure that the user marker always stays within the boundaries of the defined polygon. In case the user mov ...

Adjust the page URL during execution of a Protractor test

When conducting my protractor tests, I encountered a scenario where I needed to perform an action on page1 and then navigate to page2 in the same test script to verify the results. describe('something', function() { describe('foo', f ...

Creating a Form Layout with Bootstrap - Organizing Text Boxes and Text Areas

https://i.sstatic.net/oqRwR.jpg In the image above, I need to adjust the position of the textbox to align it with the TextArea. Is there a Bootstrap class that can help me achieve this? My current version of Bootstrap is 3.3.6. HTML &l ...

The sticky navigation and scroll to top features both function perfectly on their own, but when used simultaneously, they do not work

I'm facing an issue with two scripts on my website - when they are separate, they work perfectly fine but together, they don't seem to function properly. What could I be missing here? Script 1: window.onscroll = function() {myFunction()}; var n ...

Using Javascript's .replace() method to preserve HTML elements

This is a JavaScript function I wrote function replaceCharacters(text_input){ return text_input .replace(/O/g, 0) .replace(/I/g, 1) .replace(/o/g, 0) .replace(/i/g, 1) .replace(/t/g, 4) .replace(/d/g, 9) ...

Numerous sections with tabs on the webpage

I am in need of incorporating multiple tabbed sections on a single page, but unfortunately they are currently interconnected. When one tab is clicked, it impacts the others. To see this issue in action, you can visit: https://jsfiddle.net/pxpsvoc6/ This ...

Generate pre-set components using fundamental building blocks

Can I predefine some props for components? In my Vuetify example, let's say I want to customize the v-btn component with specific props. This custom implementation would act as a child component while still providing all the functionalities of the par ...

Implement a click event for the X-Axis label in Angular 2 Highcharts

I'm currently facing a challenge with hand-rolling a solution that involves adding a click listener to an X-Axis label in a column chart using the HighCharts API within an Angular 2+ application. Here is what I have gathered so far: I am utilizing ...

What steps can be taken to resolve the error message "t.onSubmit is not a function" that occurs upon form submission?

Upon submitting a form, it should trigger the onSubmit method function. However, an error is being returned instead: TypeError: "t.onSubmit is not a function". I've attempted to address this issue by researching similar problems and solutions provide ...

Displaying a collection of nested objects in AngularRendering a group

Is there a way to render an object of objects in Angular without converting it into an array or similar structure? I have a large object of objects and I want to avoid multiple iterations through object-to-array conversions just to loop through the array i ...

I'm having trouble with my code not working for get, set, and post requests. What could be causing this issue and how can I

Here are the TypeScript codes I've written to retrieve product details and delete them. import { Component, OnInit } from '@angular/core'; import {FormGroup,FormBuilder, FormControl, Validators} from "@angular/forms" // other impor ...

Should I use Object.assign or define class properties?

Currently in the process of developing an angular application that interacts with the twitch API. The API returns data in various formats, some of which I need to parse and save into specific classes. My main concern is understanding the potential drawbac ...

Require help with personalizing a jQuery horizontal menu

I recently downloaded this amazing menu for my first website project By clicking the download source link, you can access the code Now, I need your kind help with two issues: Issue 1: The menu seems to be getting hidden under other elements on the page ...

The pathway of information within an AngularJS modal window

Recently, I developed a small demo to demonstrate how to open a modal window in Angular using a directive as the template. However, I have some doubts about the way I am passing data and functions to the modal. Here is the code snippet from the opening c ...

I am looking for the best way to sort my JSON data based on user roles before it is transmitted to the front end using Express and MongoDB. Any

I scoured the internet high and low, but to no avail - I couldn't find any framework or code snippet that could assist me in my predicament. Here's what I'm trying to achieve: whenever a response is sent to my front-end, I want to filter th ...

Using the OR operator in an Angular filter

How can I create a filter with a range slider that shows multiple categories when it's in a certain position? I have tried using the code below to filter based on the range, but it only captures the first word after the OR operator. Can anyone provid ...

What is the best way to link the data from the HTML input to the class property in the TypeScript file? (Combining Angular and IntroJs)

I'm working on an onboarding screen with Intro.js and need help with receiving user input. I've been trying different methods like [(ngModel)] = checked, [(checked)] = checked, (checked) = checked, but haven't had any success. Can anyone pro ...

Encountering a navCtrl problem in Ionic 3 while attempting to utilize it within a service

I am currently working on a feature to automatically route users to the Login Page when their token expires. However, I am encountering an issue with red lines appearing under certain parts of my code. return next.handle(_req).do((event: HttpEvent< ...

What is the necessity of explicitly requesting certain core modules in Node.js?

The documentation explains that certain core modules are included in the Node.js platform itself and are specified within the source code. The terminology can get a bit confusing when it comes to details. The term "global objects" (or standard built-in obj ...

Every time I try to run my Angular app, it crashes. I've already tried reinstalling Node and rebooting

After attempting to relocate an angular project into a different folder yesterday, I encountered issues when trying to start the app using ng serve. Interestingly, creating a new project and running ng serve resulted in the same error. Both projects were ...