Implement a function fetchDataForUser, which fetches data from a remote JSON api and then returns a part of it.
Since this is a network call, it will need to be an asynchronous function and return the data via a callback.
The callback should be called with two arguments:
- error: if request comes back with an err, pass it through to this callback. otherwise set this to null
- data: if there is no error, this should be the object representing the wins and losses for the given username. If there is an error, this should be set to null.
*/
JavaScript
x
15
15
1
const fetchDataForUser = function (url, username, callback) {
2
request(url, (err, res, body) => {
3
if (err) {
4
callback(err, null);
5
}
6
const data = JSON.parse(body);
7
for (let key in data) {
8
console.log(data[key]);
9
if (data[key] === username){
10
return key
11
}
12
callback(null, data);
13
});
14
};
15
It returns the correct list of data from the json file: users: { mr_robot: { wins: 5, losses: 2 }, teddy_b: { wins: 0, losses: 3 } }
But I need to retrieve specific elements when entering the username: “Mr Robot” for example
JavaScript
1
3
1
+ "losses": 2
2
+ "wins": 5
3
Test driver code
JavaScript
1
2
1
fetchDataForUser(url, 'mr_robot')
2
Advertisement
Answer
You can do this without a for loop.
In my below example the line that actually matters is the userdata:
JavaScript
1
2
1
let userdata = (data["users"][username]) ? data["users"][username]: [];
2
Basically it looks to see if the username exists in the data, if so it returns that user’s data, if not it returns an empty array.
JavaScript
1
19
19
1
let data = {
2
"users": {
3
"mr_robot": {
4
"wins": 5,
5
"losses": 2
6
},
7
"teddy_b": {
8
"wins": 0,
9
"losses": 3
10
}
11
}
12
};
13
14
let username = "mr_robot";
15
16
let userdata = (data["users"][username]) ? data["users"][username]: [];
17
18
19
console.log(userdata)