jquery - Checking properties of an object in an array -


in javascript, how best way code way check if value exists in array of data?

here have:

var html = [];  html.push({     key: "/1/1.html",      value:  "html 1 data" });  if(doeskeyexist(html, "/1/1.html")) {     alert(getvalue(html, "/1/1.html")); }  function doeskeyexist(arr, key) {     $.each(arr, function (index, data) {         if(data.key === key)             return true;     });     return false; }  function getvalue(arr, key) {     $.each(arr, function (index, data) {         if(data.key === key)             return data.value;     }); } 

the above code not alert value of "html 1 data", , no error shown in console.

may please have above code?

thanks

the issue because return statements inside $.each blocks returning anonymous functions not doeskeyexist() , getvalue() functions. need change logic slightly:

var html = [];    html.push({      key: "/1/1.html",      value: "html 1 data"  });    if (doeskeyexist(html, "/1/1.html")) {      alert(getvalue(html, "/1/1.html"));  }    function doeskeyexist(arr, key) {      var result = false;      $.each(arr, function (index, data) {          if (data.key === key) {              result = true;              return; // stop loop          }      });      return result;  }    function getvalue(arr, key) {      var result = '';      $.each(arr, function (index, data) {          if (data.key === key) {              result = data.value;              return; // stop loop          }      });      return result;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -