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"
This question is related to
javascript
json
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" );
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"]);
_x000D_
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"]);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
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 = [{_x000D_
"name": "Afghanistan",_x000D_
"code": "AF"_x000D_
}, {_x000D_
"name": "Åland Islands",_x000D_
"code": "AX"_x000D_
}, {_x000D_
"name": "Albania",_x000D_
"code": "AL"_x000D_
}, {_x000D_
"name": "Algeria",_x000D_
"code": "DZ"_x000D_
}];_x000D_
_x000D_
_x000D_
function getCountryByCode(code) {_x000D_
return data.filter(_x000D_
function(data) {_x000D_
return data.code == code_x000D_
}_x000D_
);_x000D_
}_x000D_
_x000D_
var found = getCountryByCode('DZ');_x000D_
_x000D_
document.getElementById('output').innerHTML = found[0].name;
_x000D_
<div id="output"></div>
_x000D_
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.
Source: Stackoverflow.com