Search for multiple filters in JSON using Javascript forEach and indexOf

前端 未结 3 1563
孤街浪徒
孤街浪徒 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:50

    You could use an object for filters and take the keys the key to search for and the value as excact value for the string.

    Properties with commas are splitted and checked.

    function getBooks(filters) {
        return array.Books.filter(function (o) {
            return Object.keys(filters).every(function (k) {
                return o[k].split(',').some(function (v) {
                    return v === filters[k];
                });
            });
        });
        //.map(function (o) {
        //    return o.title;
        //});
    }
    
    var array = { 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" }] };
    
    console.log(getBooks({ category: 'rock' }));
    console.log(getBooks({ category: 'rock', language: 'french' }));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题