Javascript find json value

JavascriptJson

Javascript Problem Overview


I need to search inside a json list of countries. The json is like:

[ {"name": "Afghanistan", "code": "AF"}, {"name": "Åland Islands", "code": "AX"}, {"name": "Albania", "code": "AL"}, {"name": "Algeria", "code": "DZ"}]

I get from database only the code and would output the entire name. So if I get "AL" I would like to retrieve from json "Albania"

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

// the code you're looking for
var needle = 'AL';

// iterate over each element in the array
for (var i = 0; i < obj.length; i++){
  // look for the entry with a matching `code` value
  if (obj[i].code == needle){
     // we found it
    // obj[i].name is the matched result
  }
}

Solution 3 - Javascript

Just use the ES6 find() function in a functional way:

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

let country = data.find(el => el.code === "AL");
// => {name: "Albania", code: "AL"}
console.log(country["name"]);

or Lodash _.find:

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

let country = _.find(data, ["code", "AL"]);
// => {name: "Albania", code: "AL"}
console.log(country["name"]);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Solution 4 - Javascript

First convert this structure to a "dictionary" object:

dict = {}
json.forEach(function(x) {
    dict[x.code] = x.name
})

and then simply

countryName = dict[countryCode]

For a list of countries this doesn't matter much, but for larger lists this method guarantees the instant lookup, while the naive searching will depend on the list size.

Solution 5 - Javascript

Making more general the @showdev answer.

var getObjectByValue = function (array, key, value) {
    return array.filter(function (object) {
        return object[key] === value;
    });
};

Example:

getObjectByValue(data, "code", "DZ" );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTropicalistaView Question on Stackoverflow
Solution 1 - JavascriptshowdevView Answer on Stackoverflow
Solution 2 - JavascriptBrad ChristieView Answer on Stackoverflow
Solution 3 - JavascriptPenny LiuView Answer on Stackoverflow
Solution 4 - JavascriptgeorgView Answer on Stackoverflow
Solution 5 - JavascriptOsvaldo CabreraView Answer on Stackoverflow