Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Loop Through Object By Number Index Rather Than Key-Value

While looping through an object is simple using for(key in object), I'd like to access an object via an index (like an array) rather than its value.

I have a "days of the week" object composed of:

days: { sunday: "N", monday: "Y", tuesday: "N", wednesday: "Y", 
thursday: "N", friday: "Y", saturday: "N" }

I want to use a for-loop which cycles through the seven days of the week (0-6) and checks whether the object is "Y" or "N" for that day (checking the "days" object for the value at key 0 (sunday), 1 (monday), 2, 3, etc.)

for (var i = 0; i < 7; i++) { }

My problem could be solved with a bunch of if statements if i == 0 { //check sunday } else if i == 1 { //check monday } or manipulating my object into multiple arrays and going from there, however neither of these are very elegant. Is there a way to loop through the days object and access each value by a key (0 for first, 1 for second, etc.)?

like image 250
T. Tenner Avatar asked Jul 24 '26 08:07

T. Tenner


1 Answers

To iterate over the properties of an object in a consistent order, you have no choice but to use an array of the property names, for example:

var daysList = [ 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ];

And then you can iterate over the array of names:

for (let i = 0; i < daysList.length; i++) {
    let day = daysList[i];
    // do what you need with days[day]
}
like image 197
janos Avatar answered Jul 27 '26 02:07

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!