How do you iterate over a JavaScript object's properties like an array?

I don't mean using a for loop using the keys.

For example if you had an array like:

var fruitArray = ["Apples", "Bananas", "Coconuts"],
    curFruit   = 0;

You could "iterate" over that using buttons, say you've got a prev/next button and all those buttons do is decrement/increment the curFruit index.

So if I'm on Bananas, I could get Apples using the prev button using:

fruitArray[0] // Apples

Where the index was at 1 for Bananas but the prev button drops the index by one.

So with an unknown-length object, and not using a numbered-index, how could you do that?

Say it's like this:

var fruitObject = {"Apples":"Red", "Bananas":"Yellow", "Coconuts":"Brown"};

I realize you could have set 0, 1, 2 and the fruit name, but just to show that you don't know what the object key/index might be.

So if I'm on Bananas using

fruitObject.Bananas // yellow

How could I get to Apples using the same decrement idea as the Array?

My question is not about the for in method

I don't know why that's not clear, it was literally the first line in my question.

I think I found a solution anyway though it might not be direct/the most effective way to do it where I'll create a temporary local "look up".

To explain:

Here's an object

var colorObject = {"red":"apple", "blue":"blueberries", "yellow":"banana"};

I don't want to use the for in method to go from left to right complete.

I want to be able to start/keep a current position like I'm at "blue":"berries" and I can jump to "red":"apple" without knowing what "red":"apple" is

My current solution in mind is, yes, though ironically I would use the for in method but to create a look up array.

Something like

var tempArray = [];

for (var key in colorObject) {
  tempArray.push(key);
}

Then I can navigate the object starting from anywhere using the increment/decrement method.

tempArray[1] would return "blue" and I could go to "red" by doing tempArray[0] which is interpreted as

colorObject.blue // blueberries

Edit thanks to the editor for making my question more clear

I did poorly word it so that's on me.

Upvotes: 0

Views: 2135

Answers (2)

Alexander O'Mara
Alexander O'Mara

Reputation: 60587

This is not possible. JavaScript object properties do not have a defined order, so there is no concept of Y key comes after X key.

Excerpt from EnumerateObjectProperties section of ECMAScript 2017 Draft (ECMA-262) (emphasis added):

The mechanics and order of enumerating the properties is not specified but must conform to the rules specified below.

If you were to iterate over the properties of your fruitObject object, "Bananas" may or may not come before "Coconuts", this behavior simply is not defined by the specification. There does not even appear to be a guarantee the properties will come back in the same order each time you iterate over the properties.

The only way to have a consistent order would be to have an array. Optionally, you could do this by creating an array of the properties via Object.keys.

var fruitObject = {"Apples":"Red", "Bananas":"Yellow", "Coconuts":"Brown"};

// Get the property keys in an ordered list:
var fruitObjectKeys = Object.keys(fruitObject);

// An array of properties with a consistent order:
fruitObjectKeys.forEach(function(prop) {
    console.log(prop, '=', fruitObject[prop]);
});

Note however that the JavaScript engine running the code will decide what the order of the resulting array of properties is if you do it this way.

Upvotes: 2

Gabriel
Gabriel

Reputation: 2190

Objects don't have order, so you can't say that the first element of fruitObject is "Apples", the second is "Bananas" and the third is "Cocounts".

You could get the keys as an array with Object.keys() and then do something like

var keys=Object.keys(fruitObject);
fruitObject[keys[0]];

Remember that in JS it's the obj.key is the same than obj["key"].

Upvotes: 1

Related Questions