为数组的JavaScript树创建forEach语句

时间:2018-10-17 00:37:47

标签: javascript arrays database string web

首先,我想说我是堆栈溢出的新手。如果我的问题有误,请注意我是新手。 无论如何,因此我正在创建一个纯JavaScript数据库,并且使用的字符串数组的格式与此相同:

var SampleArray = [{
  "Food" : [ "banana", "Strawberry", "grapes" ],
  "Vegitables" : [ "Carrot", "Peppers" ],
  "Words" : [ "hello", "Goodbye", "Grapes" ],
  "Adjectives" : [ "Good", "First" ]
}]

希望您能了解数组部分的要点,但真正的问题是,我如何创建一个使用诸如forEach语句之类的搜索框来查找数组中的某个变量,如"good”

注释/编辑 我已将问题移到这里How to create a search system for a tree of javascript arrays

1 个答案:

答案 0 :(得分:0)

根据问题中更新的数据库格式,您可以基于以下内容进行基本搜索:

var SampleArray = [{
  "Food" : [ "banana", "Strawberry", "grapes" ],
  "Vegitables" : [ "Carrot", "Peppers" ],
  "Words" : [ "hello", "Goodbye", "Grapes" ],
  "Adjectives" : [ "Good", "First" ]
}]

function searchDatabase(query) {

  // For each object in array
  for(var object of SampleArray) {

    // Get list values of object
    var lists = Object.values(object)

    // For each list of object
    for(var list of lists) {

      // For each item of list
      for(var item of list) {

        // Look for item matching query. Locally convert to lower case to
        // avoid case sensitivity issues
        if(item.toLowerCase().indexOf(query.toLowerCase()) !== -1) {
          return object
        }
      }
    }
  }
}

console.log('search for good', searchDatabase('good') ? 'found' : 'not found')
console.log('search for bad', searchDatabase('bad') ? 'found' : 'not found')