Search for multiple filters in JSON using Javascript forEach and indexOf

前端 未结 3 1599
孤街浪徒
孤街浪徒 2021-01-18 22:20

I have data in JSON format in which I need to perform search. There are different tags available and when I click on them it searches in JSON and returns the items which has

3条回答
  •  灰色年华
    2021-01-18 22:57

    Use can utilize Array.prototype.filter(), Array.prototype.reduce(), and String.prototype.includes() to create such a filtration system, wherein an array of filters consisting of key value pairs can progressively be added to in order to refine an array of books.

    See below for a practical example.

    // Books.
    const books = [
      {
        "title": "Book 1",
        "binding": "paperback",
        "category": "pop",
        "language": "english",
        "author": "male"
      },
      {
        "title": "Book 2",
        "binding": "hardcover",
        "category": "pop rock,electro pop",
        "language": "french",
        "author": "female"
      },
      {
        "title": "Book 3",
        "binding": "audiobook",
        "category": "soft rock",
        "language": "german",
        "author": "male,female"
      },
      {
        "title": "Book 4",
        "binding": "boxed set",
        "category": "rock,classic rock",
        "language": "english",
        "author": "female,male"
      },
      {
        "title": "Book 5",
        "binding": "paperback",
        "category": "electro pop,rock,classic rock",
        "language": "french",
        "author": "male/female"
      },
      {
        "title": "Book 6",
        "binding": "paperback",
        "category": "rock",
        "language": "french",
        "author": "male"
      }
    ]
    
    // Query.
    const query = (books, filters) => {
    
      // filters = [{key: 'category', value: 'string'}..]
    
      return books.filter((book) => {
    
        // Found?
        return filters.reduce((found, filter) => {
          if (!(book[filter.key].includes(filter.value))) return false
          return found
        }, true)
    
      })
    
    }
    
    // Log.
    console.log('Category = Rock', query(books, [{key: 'category', value: 'rock'}]))
    console.log('Category = Rock + Language = French', query(books, [{key: 'language', value: 'french'}]))
    
    console.log('Paperback', query(books, [{key: 'binding', value: 'paperback'}])) // Paperback.
    console.log('Paperback + Male', query(books, [{key: 'binding', value: 'paperback'}, {key: 'author', value: 'male'}])) // Paperback + Male.
    console.log('Paperback + Male + Pop', query(books, [{key: 'binding', value: 'paperback'}, {key: 'author', value: 'male'}, {key: 'category', value: 'pop'}])) // Paperback + Male + Pop.

提交回复
热议问题