2

I have the following var, which is an object:

var users = {};

I insert users in this object like this:

users["john"] = "johns property";
users["mike"] = "mikes property";
users["luke"] = "lukes property";

I've read many questions here, and I've learned that you can't access objects directly by index. Ok, no problem, because I need to pick any random object from this "array of objects" (if that's the right expression).

More specifically, I want to pick any random object from the collection, it can be john, mike or luke, whichever. I know I can use a random number generator to get a random index, but then I won't be able to access an object from the collection using the index; so I'm looking for directions.

2
  • 5
    Get keys using Object.keys(). Get random number from 0 to the no. of keys - 1. Get the value of the key at that index in keys. Commented Dec 13, 2016 at 4:30
  • 1
    Object.keys(users) is a starting point ... oops, Tushar beat me to it Commented Dec 13, 2016 at 4:30

1 Answer 1

2

hi try following...

var users = {};

users["john"] = "johns property";
users["mike"] = "mikes property";
users["luke"] = "lukes property";

var index = Object.keys(users);

console.log(users[index[Math.floor(Math.random()*index.length)]]);
Sign up to request clarification or add additional context in comments.

Comments

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.