代码之家  ›  专栏  ›  技术社区  ›  Jakegarbo

搜索值和返回键在JavaScript中只有匹配项

  •  -1
  • Jakegarbo  · 技术社区  · 5 年前

    嗨,我试图创建一个关键字匹配使用其值的搜索建议。 函数的结果必须返回仅与其值匹配的键

    样本阵列:

    const arr = [
     { name:'Ferdinand Marlon', gender:'male',  status:'active' },
     { name:'Acey Fe', gender:'female',status:'inactive' },
     { name:'Ferry Mario', gender:'male',  status:'active' },
     { name:'Bernard Razo', gender:'male',  status:'active' },
    ]
    

    要调用的函数:

    function getKeysInMatchesInValue(arr,searchValue){
      //execute search
    }
    

    const t1 = getKeysInMatchesInValue(arr,"Ma")
    
    //expected result [ 'name', 'gender' ]
    
    const t2 = getKeysInMatchesInValue(arr,"Fe")
    
    //expected result [ 'name', 'gender' ]
    
    const t3 = getKeysInMatchesInValue(arr,"Fer")
    
    //expected result [ 'name' ]
    
    const t4 = getKeysInMatchesInValue(arr,"Ber")
    
    //expected result [ 'name' ]
    
    const t5 = getKeysInMatchesInValue(arr,"Ac")
    
    //expected result [ 'name','status' ]
    

    谢谢您!希望有人能帮忙。

    0 回复  |  直到 5 年前
        1
  •  0
  •   Sachin    5 年前

    我没有得到搜索键背后的用例,但是下面的代码应该适合您。假设钥匙可以是任何东西,而不仅仅是姓名、性别和身份。

    const arr = [
     { name:'Ferdinand Marlon', gender:'male',  status:'active' },
     { name:'Acey Fe', gender:'female',status:'inactive' },
     { name:'Ferry Mario', gender:'male',  status:'active' },
     { name:'Bernard Razo', gender:'male',  status:'active' },
    ]
    
    function getKeysInMatchesInValue(arr,searchValue){
      //execute search
      let keys = [];
      arr.forEach((elem) => {
        let arrayObjKeys = Object.keys(elem);
        arrayObjKeys = arrayObjKeys.filter((k) => {
            if(elem[k].toLowerCase().includes(searchValue.toLowerCase())){
                return true;
          }
        })
        keys = [...keys, ...arrayObjKeys];   
      })
      return [...new Set(keys)];   //eliminate duplicates
    }
    
    const t1 = getKeysInMatchesInValue(arr,"Ma")
    console.log(t1)
    //expected result [ 'name', 'gender' ]
    
    const t2 = getKeysInMatchesInValue(arr,"Fe")
    console.log(t2)
    
    //expected result [ 'name', 'gender' ]
    
    const t3 = getKeysInMatchesInValue(arr,"Fer")
    console.log(t3)
    //expected result [ 'name' ]
    
    const t4 = getKeysInMatchesInValue(arr,"Ber")
    console.log(t4)
    //expected result [ 'name' ]
    
    const t5 = getKeysInMatchesInValue(arr,"Ac")
    console.log(t5)
    

    https://jsfiddle.net/ahedxzcs/