Anthony
Anthony

Reputation: 14269

How to find out which place in an object a given property is in Javascript

For example, if I have an object like:

{"angeredoutsidecontrol":"1","difficultiespileup":"2"}

And then later in a for loop I can access the key of angeredoutsidecontrol , how can I get the value returned as 0, which would represent which place in the object this key is?

Upvotes: 1

Views: 81

Answers (3)

Jarek Kulikowski
Jarek Kulikowski

Reputation: 1389

var myMoods = ["angeredoutsidecontrol","difficultiespileup"];

and

myMoods.indexOf( 'angeredoutsidecontrol' ) 

gives you position in your list

Upvotes: 0

Paul Cuddihy
Paul Cuddihy

Reputation: 567

The order of JSON objects is not maintained, so you can't do this.

[Is the order of elements in a JSON list maintained?

Upvotes: 0

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10356

There is no guaranteed order for keys of an object.

Definition of object from an old - but still effective in this case - documentation:

4.3.3 Object

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

If order really matters to you, use array instead. For example:

[{ "angeredoutsidecontrol": "1" }
 { "difficultiespileup": "2" }];

Upvotes: 2

Related Questions