簡體   English   中英

檢查對象鍵和值是否包含某些單詞

[英]Check if Object Key and value contain certain words

我有一個帶有問題和答案對的 JSON 文件:

{
  "faq": {
    "How old is John?": "John is 30",
    "What color are Anna's eyes": "They are Blue",
    "What's the name of Anna and John child?": "His name is jack"
  }
}

如何為 John、Anna 和 Jack 過濾對象?

尋找約翰:

{
  "faq": {
    "How old is John?": "John is 30",
    "What's the name of Anna and John child?": "His name is jack"
  }
}

搜索 Anna 應該返回:

{
  "faq": {
    "What color are Anna's eyes": "They are Blue",
    "What's the name of Anna and John child?": "His name is jack"
  }
}

尋找傑克:

{
  "faq": {
    "What's the name of Anna and John child?": "His name is jack"
  }
}

有沒有辦法在鍵和值中搜索單個單詞?

這應該做你想做的。

 const that = { "faq": { "How old is John?": "John is 30", "What color are Anna's eyes": "They are Blue", "What's the name of Anna and John child?": "His name is jack" } } const filterKVcontains = (obj, str) => Object.fromEntries( Object.entries(obj).filter( e => e.some( it => (new RegExp(str, 'i')).test(it) ) ) ) const filtered = filterKVcontains(that.faq, 'john') const demo = document.createElement('pre') demo.innerHTML = JSON.stringify(filtered, null, 2) document.body.appendChild(demo)

讓我們關注變量obj ,我們把它給

  • Object.entries()返回一個由obj的屬性組成的數組,其中每個元素本身就是一個包含兩個條目的數組,一個用於鍵,另一個用於值。

我們將這個 k/v 條目數組傳遞給

  • Array.prototype.filter()只返回它所操作的數組元素,滿足它作為參數接收的函數中定義的標准。 我們在鍵/值對列表上運行它,條件如下:

    • Array.prototype.some()如果數組的至少一個元素(現在我們的鍵/值對)滿足通過函數作為參數給出的條件,則返回 true:

      • RegExp.prototype.test()如果輸入的字符串與它運行的正則表達式匹配,則返回 true。 我們的正則表達式是圍繞str構建的,它是filterKVcontains的參數
  • Object.fromEntries()從過濾的鍵/值條目列表中跳出並重建對象

假設你的對象是

const that = {
  "faq": {
    "How old is John?": "John is 30",
    "What color are Anna's eyes": "They are Blue",
    "What's the name of Anna and John child?": "His name is jack"
  }
}

您可以過濾包含“John”的鍵

Object.keys(that.faq).filter(e => e.indexOf("John") >= 0)

“安娜”

Object.keys(that.faq).filter(e => e.indexOf("Anna") >= 0)

等等

這是一個簡單的函數。它檢查對象中的每一對,如果鍵或值匹配,它將在新對象中返回。

const search = (term) => {
    let results = {};
    for (item in data.faq) {
        if (item.toLowerCase().includes(term.toLowerCase()) || data.faq[item].toLowerCase().includes(term.toLowerCase())) {
            results = {...results,[item]:data.faq[item]};
        }
    }
    return {faq: results};
}

暫無
暫無

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

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