[JS] 搜尋物件中所有值

 解法原文

https://stackoverflow.com/questions/8517089/js-search-in-object-values/50181192

function search(arr, s){
    var matches = [], i, key;
    
    for( i = arr.length; i--; )
        for( key in arr[i] )
            if( arr[i].hasOwnProperty(key) && arr[i][key].indexOf(s) > -1 )
                matches.push( arr[i] );  // <-- This can be changed to anything

    return matches;
};

// dummy data
var items = [
      {
        "foo" : "bar",
        "bar" : "sit"
      },
      {
        "foo" : "lorem",
        "bar" : "ipsum"
      },
      {
        "foo" : "dolor",
        "bar" : "amet"
      }
];
    
var result = search(items, 'lo'); // search "items" for a query value
console.log(result); // print the result


======================

改成TS寫法,並且將大小寫也能搜尋到


arr為要傳入的arry object

s為要搜尋的值

  function search(arr, s) {
      const matches = [];
      const sLow = s.toLowerCase();

      for (let i = arr.length; i--; ) {
        for (const key in arr[i]) {
          if (
            arr[i].hasOwnProperty(key&&
            arr[i][key].toLowerCase().indexOf(sLow> -1
          ) {
            matches.push(arr[i]);
          }
        }
      }

      return matches;
    }










留言

這個網誌中的熱門文章

[Angular] 閒置登出作法

[Angular Materail] 檔案上傳範例

[Angular Material] 搜尋式下拉選單範例