Exploring techniques for navigating through deeply nested JSON arrays

Struggling with diving deep into the third level of an API's JSON structure, I initially attempted to use a certain method without success. Encouraged to explore the Loadash library, I integrated it into my code but encountered issues. Seeking assistance to identify what's causing the problem.

Edit

In an effort to provide more clarity on my requirements, I have included HTML code below as previous responses have not met my expectations.

<temlate>
      <div>
        <div class="col-lg-6">
             <input type="email"
                    class="form-control-in"
                    id="exampleInputEmail1"
                    aria-describedby="emailHelp"
                    placeholder="search"
                    v-model="search">
         </div>

        <div class="page-output" v-for="(asset, i) in doFilter" :key="i">
             <target-body :asset="asset"
                    :search_by="search_by"></target-body>
        </div>
      </div>
    </template>

    domainAssets = 
    [
       {
          "id":122,
          "name":"Game",
          "web_technologies":[
             {
                "name":"RequireJS",
                "categories":[
                   "JavaScript Frameworks"
                ]
             }
          ]
       },
       {
          "id":123,
          "name":"Game2",
          "web_technologies":[
             {
                "name":"Composer",
                "categories":[
                   "PHP Frameworks"
                ]
             }
          ]
       }
    ]
    

Utilizing vuejs for search functionality:

//...
    data(){
       return {
          search_by: 'web_technologies',
          search: 'PHP',
       }
    },

    computed: {
      ...mapState({
          domainAssets: state => state.Domain.domainAssets
      }),
      
      doFilter(){
        let self = this;
        return this.domainAssets.filter(function(domain){
          if(self.search_by == "web_technologies"){
             return _.includes(_.get(domain.web_technologies, self.search_by), self.search.toLowerCase());
          }
        }
      }
    //..
    

Answer №1

To achieve this, you can utilize standard array methods. Look for the object where one of the categories within the web_technologies objects contains the specified target string...

let searchBy = 'web_technologies'

function findDataWithCategory(category, data) {
  return data.find(datum => {
    return datum[searchBy].some(wt => {
      let searchableCategories = wt.categories.map(c => c.toLowerCase())
      return searchableCategories.some(cat => cat.includes(category.toLowerCase()))
    })
  })
}

const data = [{
    "id": 122,
    "name": "Game",
    "web_technologies": [{
      "name": "RequireJS",
      "categories": [
        "JavaScript Frameworks"
      ]
    }]
  },
  {
    "id": 123,
    "name": "Game2",
    "web_technologies": [{
      "name": "Composer",
      "categories": [
        "PHP Frameworks"
      ]
    }]
  }
]

console.log(findDataWithCategory('pHp', data))

EDIT enhanced to support case insensitive search. An alternative approach (left for the reader to explore) would be to pre-calculate a searchableCategories property in the data upon initial reception. Further modifications include checking for substrings and utilizing a variable 'searchBy' key.

Answer №2

Utilizing lodash can be helpful, but it is important to ensure that your parameters are correct. When using _.get, simply provide the root element followed by the path to the child. Since you are searching for a specific part of an item, consider using the join method to convert the list into a string. Additionally, include an || operator to check for normal cases – attempting to search for 'PHP'.toLowerCase() would not function as expected even within a string context.

return domainAssets.filter(function(domain){
  if((self.search_by == "web_technologies"){
     return _.includes(_.get(domain, 'web_technologies[0].categories').join(), search.toLowerCase()) || _.includes(_.get(domain, 'web_technologies[0].categories').join(), search);
  }
})

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

What could be the reason for the sudden failure of my jQuery + AJAX functionality?

As a novice in JavaScript/jQuery/AJAX, I have a suspicion that the issue lies in some typo that I may have overlooked. Everything was working perfectly, but when I made some edits, the hide() + show() methods stopped functioning (I tested it on both Firefo ...

Creating a single page application in Angular2+ using JSON data

I am looking to create an Angular JS application using the provided JSON structure: { name: 'App Name', pages: [ { name: 'Home', url: '/', layout: { type:'HTMLElement' tag:'div ...

Exploring the Method of Accessing data-* Attributes in Vue.js

I have a button that, when clicked, triggers a modal to open. The content displayed in the modal is determined by the data attributes passed to the button. Here is my button: <button class="btn btn-info" data-toggle="modal" data-t ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

Vibrant progress bar design with CSS

Could someone assist me in coding a multicolor progress bar? I would like it to display red when the progress is less than 50, green when the progress is between 50 and 90, and blue when the progress is between 90 and 100. How can I achieve this? ...

Adding color dynamically to text within ion-card based on a regex pattern

My goal is to enhance the appearance of certain text elements by wrapping them in a span tag whenever a # or a @ symbol is detected, creating the look of usernames and hashtags on Twitter. Below is the code I am currently using: TS FILE: ngOnInit(): void ...

Building a hybrid application in Angular using UpgradeModule to manage controllers

I am currently in the process of upgrading a large AngularJS application using UpgradeModule to enable running AngularJS and Angular 6 simultaneously without going through the preparation phase, which typically involves following the AngularJS style guide. ...

"What is the best way to store the last three lines of text from a textarea into three separate variables

I am working with an HTML file that contains a textarea tag. My goal is to copy and paste text with multiple lines into the textarea and then use JavaScript to extract the last three lines into three separate variables. The textarea has the id "txt" a ...

execute the middleware function within the router

I've integrated sessions in my express.js application using Mozilla's client-sessions and I'm encountering an issue. My post and get requests are in router.js, while the middleware is in app.js. When I try to run it, I receive the following ...

Transferring information to a server with node.js

I have implemented AJAX to send data to the server. The code snippet I am using is: function post(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('POST', url); req.onload = function() ...

Is it possible to include multiple API routes within a single file in NextJS's Pages directory?

Currently learning NextJS and delving into the API. Within the api folder, there is a default hello.js file containing an export default function that outputs a JSON response. If I decide to include another route, do I need to create a new file for it or ...

Exploring the impact of naming variables in JavaScript versus not naming them

"use script"; var user = { name: "John Doe", career: "Civil Engineer", socialMedia: { fb: "www.facebook.com/johndoe", twitter: "www.twitter.com/johndoe" }, about: function() { console.log("My name is " + this.na ...

This TypeScript error occurs when the props are not compatible and cannot be assigned to

Hello fellow Internet dwellers! I am a novice in the world of coding and TypeScript, seeking some assistance here. I am attempting to extract an array of objects from props, transform it into a new object with specific information, and then return it - ho ...

Reveal the concealed element

My webpage features a hidden span element within a div that I would like to reveal when a button is clicked. However, the functionality is not working as expected. Here is my code: <!DOCTYPE html> <html> <head> <meta charset="ut ...

Keep an ear out for socket.io within an Angular application

I am trying to connect socket.io with my angular application. I have come across some examples of creating a service that can be accessed by the controller, and I understand that part. However, I am looking for a solution where all controllers can respond ...

Acquire the item that is found in every array (Javascript)

In my data, I have multiple arrays like the following: { names: [0, 1, 2], gender: [2, 5, 1], boolean: [7, 2, 1, 6] } Is there a way to extract the value that appears in all arrays? For example, how can I retrieve the value 1 since it is prese ...

Preserving the most recent choice made in a dropdown menu

Just started with angular and facing an issue saving the select option tag - the language is saved successfully, but the select option always displays English by default even if I select Arabic. The page refreshes and goes back to English. Any assistance o ...

What's the best way to format text as bold in a .ts file so that it appears as [innerText] in the HTML section?

When looking to emphasize specific text without using [innerHTML], what is the alternative method besides the usual line break changes in the interface? How can we make certain text bold? For instance: .ts file string = This is a STRING bold testing.&bso ...

How to manage list items in multiple columns in Vue.js without using v-if and v-for for displaying, adding, editing, and deleting items

As a newcomer to Vue.js, I am trying to find a way to display new items in a list while ensuring that each item is placed in separate divs based on their "category" property. Additionally, I want to provide users with the option to edit or delete each it ...

What are the differences between using attachShadow with the "mode" set to open compared to closed

I've recently delved into the world of Shadow DOM through some casual video watching. It seems like many people are quick to dismiss this feature, with comments like "Just keep it open" and "It's less flexible when closed." attachShadow( { mode ...