Filtering an array within an array based on user input

I am currently facing a challenge in filtering the child elements of an array. I am puzzled on how to specifically target children elements. So far, my filter is only functioning at the top level.

Array:

options: [
                    {name: 'Выход детали из строя в процессе эксплуатации', value: null,
                        children: [{name: 'Увеличение зазора, люфт (дробь/стуки)', value: 53},
                                    {name: 'Обрыв детали', value: 54}]},

                    {name: 'Поломка при установке', value: null},

                    {name: 'Брак до установки', value: null,
                        children: [{name: 'Недокомплект', value: 55},
                                    {name: 'Заводской брак (замятия, отсутствие резьбы, пробой пыльника и т.д.)',
                                        value: 56}]},

         ],

List output:

    <div v-if="areOptionsVisible"
         :style="{maxHeight: maxHeight, overflow: 'auto', zIndex: zIndex}"
         class="w-autocomplete__items">
        <div v-for="option in filteredOptions" class="w-autocomplete__item_first" >
            {{ option.name }}

                <div v-for="item in option.children" class="w-autocomplete__item"
                    :class="{'w-autocomplete__item_active': currentIndex === item}"
                    @mouseenter="setActive(item)"
                     @keyup.up="changeCurrent('up', item)"
                     @keyup.down="changeCurrent('down', item)"
                     @click="doChoose(item)">
                    {{ item.name }}
                </div>
        </div>
    </div>

Filter:

computed: {
        filteredOptions(){
            return this.options.filter(elem => {
                return elem.name.toLowerCase().includes(this.searchText.toLowerCase());
            });
        },
    },

Answer №1

Utilize the flatMap method to flatten and map the array while applying a filter within it:

computed: {
        filteredOptions(){
           return this.options.flatMap(option => {
               return option.children;
            }).filter(elem => {
            return elem && elem.name.toLowerCase().includes(this.searchText.toLowerCase());
         });
        },
    }

JS Example

let options = [{
    name: 'smith',
    value: null,
    children: [{
        name: 'john',
        value: 53
      },
      {
        name: 'Обрыв детали',
        value: 54
      }
    ]
  },

  {
    name: 'foobar',
    value: null
  },

  {
    name: 'foo',
    value: null,
    children: [{
        name: 'bar',
        value: 55
      },
      {
        name: 'aaaa',
        value: 56
      }
    ]
  },

]

let filtered =
  options.flatMap(option => {
    return option.children;
  }).filter(elem => {
    return elem && elem.name.toLowerCase().includes('bar');
  })

console.log(filtered)

Answer №2

It's important to apply the filter function on the children elements. To achieve this, I suggest modifying your outer filter to a map and then use filter inside it as shown below.

return this.options.map(elem => {
   return elem.children.filter(childElem => {
     return childElem.name.toLowerCase().includes(this.searchText.toLowerCase());
   });
});

Answer №3

Give this a shot.

options.forEach(function(option) {
      return option.children.forEach(function(child) {
         return child.label
    })
    })

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

Can you explain the distinction between compiled and interpreted programming languages?

Despite my efforts to research the topic, I am still confused about the distinction between a compiled language and an interpreted language. It has been mentioned that this is one of the distinguishing factors between Java and JavaScript. Can someone ple ...

Enhancing jQuery Functionality with Parameter Overrides

While it may seem like a simple question, I am new to writing jQuery plugins and could use some clarity on scope rules in JavaScript. My goal is to create a jQuery plugin that interacts with the Stack Overflow API. I have started exploring the Flair API f ...

Troubleshooting Date Problems in Angular

When using the HTML5 date picker, I have encountered an issue where after choosing a date, the ng-model displays an older date instead of the current one selected. <input type="date" ng-model="dateModel" /> For example, when selecting the current d ...

Error: Attempting to append a child to a non-existent property

I am currently learning Java Script and this is the code I have been working on. <!doctype html> <html> <head> <style> div {position:absolute; width:500px; height:500px} img {position:absolute} ...

Package videojs along with the videojs-ima extension

For a few days now, I have been struggling to create a single JavaScript file that contains all the necessary components to play videos with Google IMA ads. However, I keep encountering errors, particularly player.ads is not function, which seem to be rela ...

Tips on connecting data within a jQuery element to a table of data

I am currently developing a program that involves searching the source code to list out element names and their corresponding IDs. Instead of displaying this information in alert popups, I would like to present it neatly within a data table. <script> ...

Transferring data securely via URLs

I need advice on securing a JavaScript function that passes values into URLs in order to navigate to another page. What precautions should I implement to prevent manipulation of this process? This is the code snippet I am currently using: window.location ...

CSS code for vertical navigation arrows to remain on both the left and right sides of the webpage

I'm struggling a bit with the CSS. I want to recreate the same effect as seen on . The left and right navigation arrows stay fixed vertically even when scrolling up or down the page. Does anyone have any code examples for that? ...

Tips for extracting the most deeply nested object in a JSON file using JavaScript

Is it possible to access the innermost object without knowing the path names? Consider this JSON example: const data = { first: { second: { third: {innerObject} } } ...

After generating the dist folder using Webpack, how can we then transfer the bundle.js and css file into the statics folder?

When I execute the command npm run build or npm run build-dev After running these commands, the index.html, manage2.bundle.js, and manage2.css files are generated in the root directory. However, I need to move these files into the static directory for pro ...

Substitute link with asynchronous JavaScript and XML

I need to enable/disable user accounts by clicking on an anchor. The list of users is created dynamically using a loop. Here's an example of an anchor tag: <a href="http://www.example.com/users/deactivate/44" class="btn btn-success" title="Deactiv ...

Unable to locate the JavaScript files within the NextJs and ReactJs project

I've encountered an issue when trying to import js files (which are libraries) in my project. I am currently using NextJS version 14.1.3 and ReactJS version 18.2.0. You can find the path to these files here Here is a glimpse of the project structure ...

Issue: Vue.js is not recognizing the proxy configuration in vue.config.js file

I have tried extensively to find a solution to this issue by searching and reading through various documentation, but unfortunately, I have been unable to make it work. You can find more information on the topic at https://cli.vuejs.org/config/#devserver-p ...

Retrieving data from a database using PHP and presenting it in a loop for showcasing in JavaScript

I am currently working on a code and trying to achieve the following output: { title:"<?php echo $sender_fullname; ?>", mp3:"link", }, I want to display this in JavaScript using PHP. // Include database require_once "db.php"; // Get email ...

Angular Form Validation: Ensuring Data Accuracy

Utilizing angular reactive form to create distance input fields with two boxes labeled as From and To. HTML: <form [formGroup]="form"> <button (click)="addRow()">Add</button> <div formArrayName="distance"> <div *n ...

Using jQuery's each method to implement dynamic fallback with JSON data

Is it possible to set a fallback function dynamically from an AJAX JSONP call? I've been trying, but it doesn't seem to work. I'm not sure if I'm doing it right. Here's what I have: var GetFacebookData = function (data) { ...

Moving the starting directory of a NodeJS application on Azure

My NodeJS app on Azure was initially written in Javascript with the app.js file located in the root directory. This file was automatically detected during deployment via Git. Recently, I converted the app to Typescript and now have a build directory, with ...

The Vue.js reactivity system does not detect changes when a property is updated within a WebRTC callback

Is Vue.js component creation becoming a challenge for you? Imagine creating a small component that requires permissions for the camera and microphone from the user, displaying that stream on a canvas. Sounds simple, right? However, let's face reality ...

Experimenting with parallelism using TypeScript/JS

Currently, I am tackling a TS project that involves testing concurrent code and its interactions with a database, specifically focusing on idepotency. My goal is to ensure that multiple requests modifying the same resource will either apply changes correct ...

Running jQuery in AngularJS partialsHow can I incorporate jQuery into AngularJS partials?

I'm currently leveraging the power of the Angular UI router to divide my web pages into partial views and load them accordingly. However, I've run into an issue where I can't seem to utilize jQuery within these partial views. My approach inv ...