I have a coding dilemma where I need to extract specific information from a .json file in JavaScript and load it into an array.
function loadContacts(filter) {
var contacts = (function () {
var contacts = null;
$.ajax({
'async': false,
'global': false,
'url': 'userdata/' + username + '.json',
'dataType': "json",
'success': function (data) {
contacts = data;
}
});
return contacts;
})();
//filter code goes here, not necessary for this example
}
In my case, I have a user ID number stored as a variable (userid = 99
). The example .json
file I am working with looks like this:
[{"firstName":"Ryan","lastName":"Butterworth","id":"99"},{"firstName":"John","lastName":"Doe","id":"101"}]
My challenge is to modify the loadContacts
function above so that it only retrieves the information from the .json file where the id matches 99. This means the function should return
{"firstName":"Ryan","lastName":"Butterworth","id":"99"}
and store it in the contacts
array.