[Vuejs]-How to search nested level JSON array

3👍

It can be done with standard array methods. Find the object where one of the web_technologies objects’ categories contains the 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 improved to allow case insensitive search. A probably better way to do this (left to the reader) is to add a searchableCategories property to the data ahead of time, just once, when it’s received. Edited again to check for substrings and to have a variable ‘searchBy’ key.

👤danh

0👍

You can use lodash but your parameters aren’t right. First for _.get you should just give the root element and then the path to the child. Next because you are looking for a part of an item I’d use join to turn the list into a string. Finally add an || so that you can check for normal case, you were searching for 'PHP'.toLowerCase() which even in a string wouldn’t work

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);
  }
})

Leave a comment