Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
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')
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda