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

GetServerSideProps function yielding varied prop values

I'm currently exploring NextJS and delving into SSR. I've been struggling to grasp the functionality of getServerSideProps(). It seems that it should replace useState in order to be rendered on the backend, but I'm receiving different props ...

"Enhancing User Experience with Angular 2: Customizing Component Selection and Sty

I am currently working on an Angular application that fetches a configuration file in .json format. My goal is to dynamically choose components and apply inline styles to them. Below is an example of the structure of the configuration data obtained from a ...

Design a table within an mdDialog that allows for editing of data presented in JSON format

I'm attempting to implement a dialog using JSON data. $scope.showAttributeData = function(data) { $scope.feature = data console.log($scope.feature) var that = this; var useFullScreen = ($mdMedia('sm') ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

Adjust the map automatically as the cursor approaches the map's edge in Google Maps API V3

My latest project involved creating a selection tool using the Rectangle shape tool. With this tool, users can easily select markers by drawing a rectangle over them and releasing their mouse to erase the selection (similar to selecting items on a desktop ...

What could be the reason for a querySelector returning null in a Nextjs/React application even after the document has been fully loaded?

I am currently utilizing the Observer API to track changes. My objective is to locate the div element with the id of plTable, but it keeps returning as null. I initially suspected that this was due to the fact that the document had not finished loading, ...

Struggling with implementing the group by feature in AngularJS?

Currently, I am trying to group a select-window by 2 different object arrays - subcategories and rootcategories. Each subcategory has a relation id that links to the rootcategory's id. My goal is to have the dropdown window group the subcategories bas ...

Distance between cursor and the conclusion of the text (autofocus)

I discovered a method to automatically position the cursor at the end of a string using autofocus: <input name="adtitle" type="text" id="adtitle" value="Some value" autofocus="" onfocus="this.setSelectionRange(this.value.length,this.value.length);"> ...

Retrieve the data from an HTTP Request using AngularJS

I've been working on creating a JavaScript function that sends an HTTP Request to retrieve data, but I'm struggling with how to handle and use the result in another function. Here are the two functions I've tried (both intended to achieve t ...

Utilizing Ionic Storage to set default request headers through an HTTP interceptor in an Angular 5 and Ionic 3 application

I'm attempting to assign a token value to all request headers using the new angular 5 HTTP client. Take a look at my code snippet: import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ...

Is it possible to transfer the style object from PaperProps to makeStyles in Material UI?

I am working with a Material UI Menu component and attempting to customize its border. Currently, I am only able to achieve this customization by using PaperProps inline on the Menu element. However, I already have a makeStyles object defined. Is there a ...

Securing access across multiple routes in a React application

I am facing a challenge in my React app where I need to verify the logged-in state before allowing access to multiple routes. Despite consulting various resources like Stack Overflow for solutions such as creating a Private Route, I have only found example ...

Toggle the visibility of a table column based on user selection in Vue.js

I am having issues with displaying and hiding based on checkbox click events. Can anyone assist in identifying the mistake? When clicking on an ID, it should hide the ID column. Similarly, clicking on "first" should show/hide based on checkbox clicks, and ...

Create dynamic transitions for hidden elements using a special technique

Is it possible to smoothly transition a div element from display:none to display:block? I attempted to first set the display to block and then apply a transition, but it doesn't seem to be working as expected. HTML <input type="text" class="inp"& ...

One of the great features of Next.js is its ability to easily change

At the moment, my dynamic path is configured to display events by their ID [id].js localhost:3000/event/1 But I would like it to be structured as follows: localhost:3000/city/date/title. All of this information is available in the events database, but I&a ...

Attempting to dynamically update the image source from an array when a click event occurs in a React component

Has anyone successfully implemented a function in react.js to change the image source based on the direction of an arrow click? For instance, I have an array set up where clicking the right arrow should move to the next image and clicking the left arrow s ...

Tips for creating a tailored Express.js request interface using Typescript efficiently

I have been working on designing a custom Express request interface for my API. To achieve this, I created a custom interface named AuthRequest, which extends Request from Express. However, when attempting to import my interface and define req to utilize t ...

Display various React components for widgets

I am looking to display multiple instances of a widget in html. I have 3 divs with the same id, each with different attributes, and I want to render my react component three times on the page. Currently, I am only able to display the first component. Here ...

What advantages come from destructuring in conjunction with require statements?

When utilizing require, is there a performance advantage or disadvantage to importing the entire module versus only importing selected functions? It's my understanding that when using require to import modules (as opposed to using import), compilers ...

How can I retrieve objects using the JSON function?

I need to design a function that returns objects like the following: function customFunction(){ new somewhere.api({ var fullAddress = ''; (process address using API) (return JSON data) })open(); } <input type= ...