0

I need get random key to select different response.

I have: response.data.players["11"].name and i need random value instead of 11 because all keys are numbers.

1 Answer 1

1

You can utilize the Object.keys method in Javascript. https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

var keys = Object.keys(response.data.players);
var player = response.data.players[keys[0]];

If you want to get a random player you can use this code:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

var keys = Object.keys(response.data.players);
var player = response.data.players[keys[getRandomInt(keys.length)]];
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, and how get random?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.