Javascript find json value [duplicate]

I suggest using JavaScript’s Array method filter() to identify an element by value. It filters data by using a “function to test each element of the array. Return true to keep the element, false otherwise..”

The following function filters the data, returning data for which the callback returns true, i.e. where data.code equals the requested country code.

function getCountryByCode(code) {
  return data.filter(
      function(data){ return data.code == code }
  );
}

var found = getCountryByCode('DZ');

See the demonstration below:

var data = [{
  "name": "Afghanistan",
  "code": "AF"
}, {
  "name": "Ă…land Islands",
  "code": "AX"
}, {
  "name": "Albania",
  "code": "AL"
}, {
  "name": "Algeria",
  "code": "DZ"
}];


function getCountryByCode(code) {
  return data.filter(
    function(data) {
      return data.code == code
    }
  );
}

var found = getCountryByCode('DZ');

document.getElementById('output').innerHTML = found[0].name;
<div id="output"></div>

Here’s a JSFiddle.

Leave a Comment