Filter array of objects whose any properties contains a value

后端 未结 8 1101
你的背包
你的背包 2020-12-13 19:26

I\'m wondering what is the cleanest way, better way to filter an array of objects depending on a string keyword. The search has to be made in any properties of

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 19:42

    You could filter it and search just for one occurence of the search string.

    Methods used:

    • Array#filter, just for filtering an array with conditions,

    • Object.keys for getting all property names of the object,

    • Array#some for iterating the keys and exit loop if found,

    • String#toLowerCase for getting comparable values,

    • String#includes for checking two string, if one contains the other.

    function filterByValue(array, string) {
        return array.filter(o =>
            Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
    }
    
    const arrayOfObject = [{ name: 'Paul', country: 'Canada', }, { name: 'Lea', country: 'Italy', }, { name: 'John', country: 'Italy' }];
    
    console.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]
    console.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题