Search code examples
javascriptjqueryobjectjavascript-objects

how to retrieve key and value from object search?


function pageKeywords(searchValue){
  const pageKeywords = {
    "home": "/homepage",
    "about": "/about-us",
    "about us": "/about-us"
  }
  const getInputVal = searchValue;
  
  if (pageKeywords[getInputVal]) {
    console.log(pageKeywords[getInputVal])
    window.location.href = pageKeywords[getInputVal];
  } else {
    console.log('not found')
  }
}

                

$(document).ready(function(){
  $("#searchKeywords").on("keypress", function(e) {
    if (e.which === 13) {
      pageKeywords($(this).val())
    }
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="searchKeywords">

I want to find a page url searching by an input. I have an object that contains keywords and urls. Then when press enter it will do a check, if the keywords are the same or exist, it will display the url, if not it will display not found.

So for example in the input I type "home", when I enter it will display the url "/homepage" because the keywords are exist, if I type "contact" it will show not found because the keywords doesn't exist.

I've made the code like below but why not found appear too?

$(document).ready(function(){
  $("#searchKeywords").on("keypress", function(e){
    if(e.which == 13){   
      const map = {
        "home" : "/homepage",
        "about" : "/about-us"
      }

      const searchVal = $("#searchKeywords").val()

      Object.entries(map).map((k,v) => {
        if(searchVal == k[0]){
          console.log(k[1])
        }else{
          console.log("not found")
        }
      });
    }
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="searchKeywords">


Solution

  • Here pageKeywords is an object. So you can directly retrieve the key, but need not to use map and Object.entries. Also note You can initialise the object outside the keypress event listener & prefer using === instead of ==

    $(document).ready(function() {
    
      const pageKeywords = {
        "home": "/homepage",
        "about": "/about-us"
      }
    
      $("#searchKeywords").on("keypress", function(e) {
        if (e.which === 13) {
          const getInputVal = $(this).val().toLowerCase();
          if (pageKeywords[getInputVal]) {
            console.log(pageKeywords[getInputVal])
          } else {
            console.log('not found')
          }
        }
      });
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <input type="text" id="searchKeywords">