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.
*/
const fetchDataForUser = function (url, username, callback) { request(url, (err, res, body) => { if (err) { callback(err, null); } const data = JSON.parse(body); for (let key in data) { console.log(data[key]); if (data[key] === username){ return key } callback(null, data); }); };
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
+ "losses": 2 + "wins": 5
Test driver code
fetchDataForUser(url, 'mr_robot')
Advertisement
Answer
You can do this without a for loop.
In my below example the line that actually matters is the userdata:
let userdata = (data["users"][username]) ? data["users"][username]: [];
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.
let data = { "users": { "mr_robot": { "wins": 5, "losses": 2 }, "teddy_b": { "wins": 0, "losses": 3 } } }; let username = "mr_robot"; let userdata = (data["users"][username]) ? data["users"][username]: []; console.log(userdata)