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.

*/

JavaScript

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

Test driver code

JavaScript

Advertisement

Answer

You can do this without a for loop.

In my below example the line that actually matters is the userdata:

JavaScript

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
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement