Skip to content
Advertisement

Unable to retrieve specific elements from JSON api

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.

JSON Data: https://gist.githubusercontent.com/kvirani/f7d65576cc1331da1c98d5cad4f82a69/raw/4baad7566f0b6cd6f651c5d3558a015e226428b5/data.json

The callback should be called with two arguments:

  1. error: if request comes back with an err, pass it through to this callback. otherwise set this to null
  2. 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)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement