1

I have an object formatted like this:

Object { 111111={...}, 222222={...}, 333333={...} }

The object is called entities. I need to get a random item from this object, such as "111111" or "222222".

Here is my code now:

 var tmpList = Object.keys(entities);
 var randomPropertyName = tmpList[ Math.floor(Math.random()*tmpList.length)];
 var propertyValue = entities[randomPropertyName];

This sets propertyValue to "[object Object]". I want it to be "111111", or "222222", or "333333" etc.

1 Answer 1

2

What you are seeing is exactly correct.

randomPropertyName is returning you one of the keys from the entities object and then you are using that key as a reference to return whatever value is assigned to it in entities (using entities[randomPropertyName]).

At the beginning of your question, though, you describe the value of each of your keys as objects ({...}), so that is what propertyValue has assigned to it . . . an object.

If you want the key (e.g., "111111", "222222", etc.), then you would reference randomPropertName instead of propertyValue. . . if you want some additional data from within value stored in propertyValue, then you will have to reference it specifically by it's key like this: propertyValue.KEY_NAME or this: propertyValue[KEY_NAME].

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.