嘗試根據 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 項目)。我猜腳本不正確。

馬克

使用對象過濾器: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: "Fácil",
  },
  {
    id: 2,
    name: 'King Size Manger',
    artist: 'Josh Turner',
    level: "Fácil",
  },
  {
    id: 3,
    name: 'Legend',
    artist: 'Bob Marley',
    level: "Muy fácil",
  },
  {
    id: 4,
    name: 'Catch A Fire',
    artist: 'Bob Marley',
    level: "Muy fácil",
  },
  {
    id: 5,
    name: 'Fine Line',
    artist: 'Harry Styles',
    level: "Fácil",
  },
]

function filterSongs(filterStr = '', filterLevel = '') {

  return songs.filter(item => {
    const context = filterStr.toLowerCase()
    // Filter on level else ignore by always returning true.
    let result = filterLevel.length ? (item.level === filterLevel) : true
    
    // 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 Fácil', filterSongs('', 'Fácil'))

console.log('Search for Golden with level Fácil', filterSongs('Golden', 'Fácil'))

console.log('Search for Bob', filterSongs('Bob'))

如何使用您的示例實現上述代碼:

let filterLevel = this.context.appActions.dataSlots['ds_LevelFilter'] ?? '';
let filterStr = this.context.appActions.dataSlots['ds_SearchFilter'] ?? '';
let filterLimit = this.context.appActions.dataSlots['ds_limitQuery'] ?? 15;

function filterSongs(filterStr = '', filterLevel = '') {

  return songs.filter(item => {
    const context = filterStr.toLowerCase()
    // Filter on level else ignore by always returning true.
    let result = filterLevel.length ? (item.level === filterLevel) : true
    
    // 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

  })

}

let filteredItems = filterSongs(filterStr, filterLevel)

return filteredItems.sort((a, b) => {
  return new Date(b.date) - new Date(a.date);
}).slice(0,filterLimit);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

嘗試根據一列的值進行兩次 MySQL 計算

嘗試根據過濾器刪除 Pandas 數據框中的行時出現關鍵錯誤

XSLT:嘗試根據這兩個節點的元素值組合兩個節點

如何在react js打字稿中過濾對像數組中的數據

在 React 中根據多個條件過濾對像數組

如何過濾對像數組並根據另一個數組過濾掉值?過濾應該基於鍵而不是值

嘗試根據谷歌表格中的條件為觸發郵件創建腳本

嘗試根據 Vue 中的字符長度添加類時,計算屬性引用錯誤的“this”

如何根據特定對象過濾對像數組?

如何根據 JS 中的另一個數組導航一個數組

我正在嘗試運行一個 jQuery 代碼來根據是工作日還是周末來更改 h1 顏色

我正在嘗試根據地圖功能內的按鈕將 id 傳遞給內部組件

創建一個虛擬對象,測試幾列中的 na 值

如何根據鍵過濾對象的數據並使新數組做出反應?

根據 id 數組過濾對像數組中的 id

是否可以總結對像數組的屬性並根據另一個屬性對其進行過濾?

C# Linq 如何使用對象的數據過濾列表並將結果存儲在另一個列表中?

如何按值過濾嵌套的對像數組並獲取根對象

嘗試將數據框過濾為具有特定值的行

嘗試在畫布(JS)中更新計時器

任何人都可以建議一種通過對象鍵對對像數組進行分組的方法,然後根據 JavaScript 中的分組創建一個新的對像數組嗎?

嘗試從 JSON 數據訪問對像數組的問題

如何根據過濾器列表過濾列表,但另一個列表中的項目除外?

如何根據對象的值將對像數組拆分為另一個數組?

嘗試將對象放入 s3 存儲桶時,配置中缺少憑據

嘗試從 API 迭代嵌套對象並將數據返回到我的反應組件中

Elasticsearch 查詢匹配一個字段,但應根據另一字段過濾結果

如何根據條件參數過濾對象?

在js中將多個數組(具有相似的id)組合成一個對象