0
votes

I am looking for a way to loop through an object but starting for example some where in the middle or any other value, for example: Tue, Wen, Thu, Fri, Sat, Sun, Mon instead of Sun, Mon, Tue, Wen, Thu, Fri, Sat(as the object used in the example).

// basic week overview

daysByName = {
    sunday    : 'Sun', 
    monday    : 'Mon', 
    tuesday   : 'Tue', 
    wednesday : 'Wed', 
    thursday  : 'Thu', 
    friday    : 'Fri', 
    saturday  : 'Sat'
}

// basic loop

for (var key in daysByName) {
    console.log(daysByName[key]);
}
2
There is no order in which an object is looped through. Therefore there will be no accurate answer to your exact question. You have to choose an implementation, where you store your objects in an array.Amberlamps

2 Answers

0
votes

You cannot rely of the order of properties in an object, and the result might depend on the browser (for example properties reordered alphabetically). And you cannot rely on for...in alone to capture the properties, you need to add an hasOwnProperties() filter.

You have two alternatives:

  • use an array instead of an object

    daysByName = [ {sunday: 'Sun'}, {monday: 'Mon'}, ... ]

  • enter the index in the object itself:

    Sunday:{abbreviation:"Sun",index:0}

-1
votes

You can try something like this, where startIndex is the startIndex you want to start.

daysByName = {
    sunday    : 'Sun', 
    monday    : 'Mon', 
    tuesday   : 'Tue', 
    wednesday : 'Wed', 
    thursday  : 'Thu', 
    friday    : 'Fri', 
    saturday  : 'Sat'
}

// Obtain object length
var keys = [];
for (var key in daysByName) {
    keys.push(key)
}

// Define start index
var startIndex = 4, count = 0;
for (var key in daysByName) {
    // Index is made by the count (what you normally do) + the index. Module the max length of the object.
    console.log(daysByName[ keys[ (count + startIndex) % (keys.length)] ]);
    count++; // Don't forget to increase count.
}

Here's a fiddle: http://jsfiddle.net/MH7JJ/2/