Navigating through complex data structures of nested objects and arrays to selectively

I am currently working on a Vue project where I need to search through an array of nested objects to find a specific object based on the "title" property. The user interface includes a text input field for conducting the search operation.

The structure of the data is as follows:

const data = 
[{
    "catId": "1",
    "catTitle": "a",
    "exampleArray": [{
        "id": "111",
        "title": "aaa"
    }, {
        "id": "222",
        "title": "bbb"
    }, {
        "id": "333",
        "title": "ccc"
    }]
}, {
    "catId": "2",
    "catTitle": "b",
    "exampleArray": [{
        "id": "444",
        "title": "ddd"
    }, {
        "id": "555",
        "title": "eee"
    }]
}, {
    "catId": "3",
    "catTitle": "c",
    "exampleArray": []
}, {
    "catId": "4",
    "catTitle": "d",
    "exampleArray": [{
        "id": "555",
        "title": "fff"
    }]
}]

I have attempted the following code snippet in my search function:


return data.filter(item => {
                    return item.exampleArray.filter(element=> {
                        return element.title.toLowerCase().includes(this.search.toLowerCase())
                    })
                })

For example, if the user inputs "aaa", the expected output should be:


[{
    "catId": "1",
    "catTitle": "a",
    "exampleArray": [{
        "id": "111",
        "title": "aaa"
    }]
}]

The search functionality is designed to retrieve all matching results that meet the specified criteria.

Answer №1

Just a little bit more to go!

const data = 
[{
    "catId": "1",
    "catTitle": "a",
    "exampleArray": [{
        "id": "111",
        "title": "aaa"
    }, {
        "id": "222",
        "title": "bbb"
    }, {
        "id": "333",
        "title": "ccc"
    }]
}, {
    "catId": "2",
    "catTitle": "b",
    "exampleArray": [{
        "id": "444",
        "title": "ddd"
    }, {
        "id": "555",
        "title": "eee"
    }]
}, {
    "catId": "3",
    "catTitle": "c",
    "exampleArray": []
}, {
    "catId": "4",
    "catTitle": "d",
    "exampleArray": [{
        "id": "555",
        "title": "fff"
    }]
}];
const search = "aa";

console.log(data.filter(item => {
                    return item.exampleArray.some(category=> {
                        return category.title.toLowerCase().includes(search.toLowerCase())
                    })
                }));
                
console.log(data.map(item => {
                    item.exampleArray =  item.exampleArray.filter(category=> {
                        return category.title.toLowerCase().includes(search.toLowerCase())
                    })
                    return item;
                }).filter(a=>a.exampleArray.length>0))

I made a slight adjustment by incorporating a check for array length after your filter operation. Filter functions based on true or false conditions to determine inclusion of elements, and an empty array is considered truthy. Therefore, it's essential to verify if the array contains elements for accurate filtering.

UPDATE: I opted for using FIND instead of FILTER. Find returns a falsy value when nothing matches, but a truthy value (the found element) if there's a match. This approach saves time by stopping the loop once a match is found.

ANOTHER UPDATE: some method serves the purpose better than find, we keep learning every day! It directly returns true upon finding a match!

Answer №2

To meet this requirement, you can utilize the Array.filter() method in combination with String.includes()

Check out a demonstration below:

const data = [{
  "catId": "1",
  "catTitle": "a",
  "exampleArray": [{
    "id": "111",
    "title": "aaa"
  }, {
    "id": "222",
    "title": "bbb"
  }, {
    "id": "333",
    "title": "ccc"
  }]
}, {
  "catId": "2",
  "catTitle": "b",
  "exampleArray": [{
    "id": "444",
    "title": "ddd"
  }, {
    "id": "555",
    "title": "eee"
  }]
}, {
  "catId": "3",
  "catTitle": "c",
  "exampleArray": []
}, {
  "catId": "4",
  "catTitle": "d",
  "exampleArray": [{
    "id": "555",
    "title": "fff"
  }]
}];

const searchWord = 'aaa';

const res = data.filter(obj => {
  obj.exampleArray = obj.exampleArray.filter(({ title }) => title.includes(searchWord))
  return obj.exampleArray.length;
});

console.log(res);

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

When dealing with back-end data in JavaScript, converting long types can result in a

When parsing data of the Object type in C#, utilizing JavaScript on the front end to parse the data can result in loss of precision. <!DOCTYPE html> <html> <head> <title>Example using BigNumber.js</title> <script s ...

How are jQuery.ajax and XMLHttpRequest different from each other?

My goal is to fetch and run the script contained in a file named "example.js" using an AJAX request. Suppose the content of example.js looks like this: const greetings = { hello: "Hello", goodBye: "Good bye" } console.log(greetings.hello) In anot ...

form controls disappear upon adding form tags

Currently experiencing an issue with angular and forms that I could use some help with. I have a dynamic form that is functioning properly, but now I need to add validations to it. After following this guide, I established the structure correctly. Howeve ...

How can we utilize Javascript to add both days and years to the current date?

Is there a way to get the current date, add 1 day to it and then also add 1 year? If so, how can this be done? ...

"Using Angular, when $event is triggered on multiple child elements, each child

I am facing an issue with my html element in the application: .html <a (click)="onOpen($event)"> <i class="fa fa-file-text-o"></i> <p>Profile</p> </a> .ts onOpen(event):void { console.log( event.target ) ...

The issue of not being able to use res.flush as a function in Express-sse is

Currently, I am exploring the use of express-sse for the purpose of automatically triggering a notification and calling an API when an order is placed. Below is the code snippet for my API: router.post("/createOrder", async (req, res) => { try { ...

What is the best way to determine the total number of classes that come before a specific element

Currently, this is my approach: <script> function Answered(str) { var script = document.getElementsByClassName('Answered')[str]; if(script!==null) {script.setAttribute("style", "");} } </script> <span class=Answered style=" ...

Guide on how to retrieve a specific object element within a Vue.js list using Nuxt

I've got an array of objects structured like this: { id: 33617, datePublication: 1532266465, dateUpdate: 1532266574, headline: 'A catchy headline goes here', images: [ [Object] ] }, { id: 33614, datePublication: 1532265771, date ...

JavaScript function is returning 'undefined' instead of an integer

My JavaScript/jQuery function is not functioning correctly and instead of returning an integer, it returns undefined. function __getLastSelectedCategory(table_id) { if ( jQuery('.categories_table[data-table-id="1"]').find('td.active&apo ...

Tips for transmitting `props` information between parent and child components using react router

Looking for guidance on how to properly pass props data from a parent component to a child component when navigating to a new route. I've attempted some solutions from this GitHub issue, but passing it through {...props} didn't work as expected. ...

Concealing specific sections of HTML content in a webview on the fly

I've been experimenting with a proof of concept feature to implement the ability to conceal certain parts of a web page loaded in a webview, but I seem to be encountering some issues... Within a UIWebview extension, I have something similar to this c ...

Error: Unable to locate module 'react-calendar-heatmap'

After successfully creating a component that functioned flawlessly in my local application, I encountered an error when attempting to integrate it with npm: ./src/App.js Module not found: Can't resolve 'heatmap-calendar-react' in 'C:& ...

Vue: Show or hide components based on URL conditions

My App.vue has the following code snippet: <template> <v-app> <core-toolbar /> <core-drawer /> <core-view /> </v-app> </template> However, I need to hide <core-toolbar /> and <cor ...

IDEA 2021.2 NPM SCRIPTS: Looks like there are no scripts available

Searching through the npm scripts, I am unable to locate any, however package.json does contain: ...

Is there a way to have incoming messages automatically align to the left or right based on the sender, without using the float property?

I am currently working on a webpage where I want the messages sent by different users to appear in a yellow conversation window based on who sent them - user 1 or user 2. I want it to mimic the messaging layout commonly seen on phones, distinguishing betwe ...

What is the best way to configure a basic firebase ajax call?

I wanted to explore using AJAX instead of set to interact with Firebase. However, when I attempted to do so with the code below in my test.html file, I encountered an error message in the console: XMLHttpRequest cannot load . No 'Access-Control-Allow ...

JavaScript-based tool for extracting content from Sketch file

My goal is to extract the contents of a .sketch file. I have a file named myfile.sketch. When I rename the file extension to myfile.zip and extract it in Finder, I can see the files inside. However, when I try the same process on the server using Node.js ...

Is it necessary for TypeScript classes that are intended for use by other classes to be explicitly exported and imported?

Is it necessary to explicitly export and import all classes intended for use by other classes? After upgrading my project from Angular 8 to Angular 10, I encountered errors that were not present before. These issues may be attributed to poor design or a m ...

After several interactions, the CSS files fail to load

I'm currently utilizing jQuery Mobile with 3 pages, and I've noticed that after navigating between the pages, the CSS is not being rendered properly. LoadCss.js $(document).on("pageinit",function(event) { $("#categoriesPage").on('pages ...

Navigating through elements in an array in node.js

Within my array, I store the languages that users prefer. Here is an example: let language = [] var Lang = "it" language.push(Lang) This process is repeated with various languages. The array would eventually contain these values: language ...