1

I'm working with javascript to return the username of users that are on a API and I can make it return something like this:

{"status":200,"users":[{"ID":2,"CreatedAt":"2022-04-24T16:17:41.615941Z","UpdatedAt":"2022-04-24T16:17:41.615941Z","DeletedAt":null,"alertTime":1,"sos":false,"username":"Jarret","access_mode":1,"UserFriends":null,"UserPositions":null},{"ID":3,"CreatedAt":"2022-04-24T16:17:44.203433Z","UpdatedAt":"2022-04-24T16:17:44.203433Z","DeletedAt":null,"alertTime":1,"sos":false,"username":"Narciso","access_mode":1,"UserFriends":null,"UserPositions":null},

And I want to return only the parameter called username but it always return me undefined and I can't figure out why

Here's my code:

function showUsers() {
  var myHeaders = new Headers();
  myHeaders.append("Authorization", token);

  var formdata = new FormData();

  var requestOptions = {
    method: "GET",
    headers: myHeaders,
    data: formdata,
    redirect: "follow",
  };

  fetch("https://api.secureme.pt/api/v1/user/", requestOptions)
    .then((response) => response.json())
     //SPECIFING HERE VVVVV
    .then((result) => document.getElementById("utilizadores").innerHTML = result.username)
    .catch((error) => console.log("error", error));
}
Rui
  • 39
  • 3
  • What is `result`? Is it the object you showed above? That doesn't have a `username` property on it, it's the objects inside of `users` array that has the `username` – Nick Parsons May 26 '22 at 09:06
  • Yes result is what is showed above, so shoul I do users.username? – Rui May 26 '22 at 09:09
  • It's not really clear what the output is that you're after. The response has multiple usernames, not just one username. Do you want both? Either way, the link at the top of your question covers how to access the data in your object in the way you'll need. – Nick Parsons May 26 '22 at 09:10
  • Yes I want them all to appear – Rui May 26 '22 at 09:12
  • The array that you want to access is located in `result.users`, you can use this [From an array of objects, extract value of a property as array](https://stackoverflow.com/q/19590865) on that array to get an array of usernames – Nick Parsons May 26 '22 at 09:14

0 Answers0