Reputation: 8640
What would be the quickest way to find the position of a member in a JS object?
Let's say I have the following object:
var myObject = {
"apple": { "color" : "green", "shape" : "round" },
"banana": { "color" : "yellow", "shape" : "long" },
"orange": { "color" : "orange", "shape" : "round" },
"kiwi": { "color" : "green", "shape" : "round" }
}
Now, if I want to know the position of banana (i.e. 2), do I need to loop through the object or is there a quicker way?
Update:
Thanks to everyone, I now understand that there is no concept of "order" in an object and I cannot reliably find a position of a member. Neither do I have the possibility to find the next or previous member. That all makes perfect sense...
So the way I solved my issue is this: I looped through my array and fed the keys to an array that I can use to keep track of the members I have in the object.
var fruits = new Array();
for (var key in myObject) {
fruits.push(key);
}
Upvotes: 2
Views: 11390
Reputation: 1037
i do it this way
var position = Object.keys(myObject).indexOf('banana');
maybe it helps others...
Upvotes: 13
Reputation: 91452
You shouldn't rely on object keys having a strong ordering. It's not guaranteed by the spec, and some previous versions of Chrome didn't perserve ordering, for example.
Depending on your use case, you could either store the index, or you could keep an array around
var myObject = {
apple: { index:0, color:"green" ...
var myKeys = ["apple", "banana", ... ]
var myObject = ...
Upvotes: 1
Reputation: 245419
Technically, "banana" doesn't have a set position. You're using a JavaScript object to store your data which doesn't guarantee any order. If order is important, you should store things in an Array. You would have to do something like:
var myObjectArray = [
{ 'key' : 'apple', 'value' : { 'color' : 'green', 'shape' : 'round' } },
{ 'key' : 'banana', 'value' : { 'color' : 'yellow', 'shape' : 'long' } },
{ 'key' : 'orange', 'value' : { 'color' : 'orange', 'shape' : 'round' } },
{ 'key' : 'kiwi', 'value' : { 'color' : 'green', 'shape' : 'round' } }
]
And then to get the index:
var i;
for(i = 0; i < myObjectArray.length; i++){
if(myObjectArray[i].key === 'banana'){
return i;
}
}
Upvotes: 4
Reputation: 227230
Objects in JavaScript aren't ordered. What exactly do you want to do with this data once you get it? Because if you're looking for the 2nd value in the object, you may not always get the same thing.
Upvotes: 3