0

Assuming an object is initialized as following:

var myObj = {
   "key1":"val1",
   "key2":"val2",
   "key3":"val3",
   ...
};

Can I retrieve key values like this?

var retrKey1 = myObj[0];
var retrKey2 = myObj[1];
var retrKey3 = myObj[2];
...

The issue I am trying to solve is that I need to pick random key values from this object. Generating a random number is not an issue, but:

  1. How can I retrieve the number of keys in the object/map?
  2. Can I retrieve the key values using a integer index like in arrays?

If not, what are my options?

1
  • What happened when you tried it? Commented Sep 16, 2013 at 10:43

2 Answers 2

4

The Object.keys method returns an array of object properties. You can index the array with numbers then.

var myObj = {
 "key1":"val1",
 "key2":"val2",
 "key3":"val3",
 ...
};
var keys = Object.keys(myObj); 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Sign up to request clarification or add additional context in comments.

2 Comments

The order isn't guaranteed. You might have different results in different engines/browsers/executions.
Since the OP is looking for random key values, ordering and consistency between implementations is moot. Given a random x in 0..maxKey, their random property will be myObj[keys[x]]. I think that's exactly what they're asking for.
4

No, because there's no ordering among property keys. If you want ordered keys, you need to work with an array.

You could define a structure like this :

var myObj = [
    {key:"key1", val:"val1"},
    ...
];

3 Comments

He can use myobj['property'] too
@steo I understand from the question that OP wants to use "an integer index", not the property name.
yeah I was not blaming you

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.