簡體   English   中英

嘗試根據 JS 中的幾個字段過濾 JSON

[英]Trying to filter a JSON based on several fields in JS

首先,如果我的問題太明顯,我很抱歉,但我的知識有限,我不知道如何實現我正在嘗試的東西。 我有一個 JSON 文件作為數據(歌曲)的來源,我正在嘗試根據幾個字段(級別、名稱、藝術家等)過濾該數據。

JSON 的一些數據示例:

[
  {"artist": "Black",
    "categories": "Arreglos",
    "date": 1639127185000,
    "level": "Fácil",
    "musicStyle": "Pop/Rock",
    "name": "Wonderful Life",
    "practice": "n/a",
    "preloadID": "Wonderful_Life",
    "subtitle": "Fácil",
  },
{"artist": "",
    "categories": "Arreglos",
    "date": 1587948049309,
    "image": "./images/arreglos/a_million_dreams.jpeg",
    "level": "Fácil",
    "musicStyle": "Film/TV",
    "name": "A million dreams",
    "preloadID": "AMillionDreams_Facil",
    "subtitle": "Fácil",
  },
{"artist": "",
    "categories": "Arreglos",
    "date": 1587948046688,
    "image": "./images/arreglos/a_million_dreams.jpeg",
    "level": "Principiante",
    "musicStyle": "Film/TV",
    "name": "A million dreams",
    "preloadID": "AMillionDreams_Principiante",
    "subtitle": "Principiante",
  },
{"artist": "Vanessa Carlton",
    "categories": "Arreglos",
    "date": 1602939064030,
    "level": "Fácil",
    "musicStyle": "Pop/Rock",
    "name": "A thousand miles",
    "preloadID": "AThousandMiles_Facil",
    "subtitle": "Fácil",
  },
{"artist": "Vanessa Carlton",
    "categories": "Arreglos",
    "date": 1602939064033,
    "level": "Muy fácil",
    "musicStyle": "Pop/Rock",
    "name": "A thousand miles",
    "preloadID": "AThousandMiles_MuyFacil",
    "subtitle": "Muy fácil",
    "tonality": ""
  },
]

這是我必須嘗試過濾數據的腳本。

let filteredItems = [];
let filterLevel=this.context.appActions.dataSlots['ds_LevelFilter'];
let filterStr=this.context.appActions.dataSlots['ds_SearchFilter'];
filterStr=filterStr.toLowerCase();
      
      items.forEach(item => {
        if (item["artist"].toLowerCase().includes(filterStr) || item["name"].toLowerCase().includes(filterStr) ) {
          filteredItems.push(item);
          }
      });
      
      items.forEach(item => {
        if (item["level"] == filterLevel) {
          filteredItems.push(item);
        }
      });
      
      items = filteredItems.sort((a, b) => {
              return new Date(b.date) - new Date(a.date);
            }).slice(0,this.context.appActions.dataSlots['ds_limitQuery']);

return items;

對於 filterStr,我有一個文本字段,用戶可以在其中編寫搜索,如果名稱或藝術家中包含該字段,它應該返回結果文檔。

在 filterLevel 我有一個帶有多個值的選擇器(西班牙語中的 Easy、Medium 等),它應該等於數據中的字段“級別”。

我不確定代碼是否顯示了我正在嘗試的內容,但如果我只使用第一個 if 塊(名稱和藝術家),它會完美運行。 但是如果我添加第二個,它會給我一個重復鍵的錯誤(它是一個 React 項目)。 我猜腳本不正確。

我真的很感激一些指導。 謝謝!

使用 Object 過濾器: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

 const songs = [ { id: 1, name: 'Golden Hour', artist: 'Kacey Musgraves', level: 100 }, { id: 2, name: 'King Size Manger', artist: 'Josh Turner', level: 122 }, { id: 3, name: 'Legend', artist: 'Bob Marley', level: 100 }, { id: 4, name: 'Catch A Fire', artist: 'Bob Marley', level: 100 }, { id: 5, name: 'Fine Line', artist: 'Harry Styles', level: 68 }, ] function filterSongs(filterStr = '', filterLevel = null) { return songs.filter(item => { const context = filterStr.toLowerCase() // Filter on level else ignore by always returning true. let result = filterLevel == null? true: (item.level === filterLevel) // If result is false because level was set and did not match then skip filterStr check. // If result is true because level was ignored or matched then search if filterStr has value. if(result && filterStr.length) { result = item.artist.toLowerCase().includes(context) || item.name.toLowerCase().includes(context) } return result }) } console.log('Search for Harry', filterSongs('Harry')) console.log('Search for level 100', filterSongs('', 100)) console.log('Search for Golden with level 100', filterSongs('Golden', 100)) console.log('Search for Bob', filterSongs('Bob'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM