Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Generic For Loop

Is there any way to create a generic for loop that will loop through either an array or an object correctly? I know I can write the following for loop, but it will also loop through other properties that would be added to an array.

for (item in x) {
   console.log(item)
}

By this I mean a for loop that will iterate:

x = [1, 2]
x.foo = "foo"
y = {first:1, second: 2}

x as

1
2  

y as

first
second

The reason behind this is that I won't know until runtime what x will be (either an Array or an Object). Is my only option to create a function that will check at runtime?

like image 844
cbillingham Avatar asked Sep 19 '26 08:09

cbillingham


1 Answers

Use the for..of loop.

Iterating over arrays

const array = [1, 2];
array.foo = "test";
for (const number of array) {
    console.log(number); // skips array.foo
}

Iterating over objects

const object = {
    some: "string",
    number: 42
};
for (const [key, value] of Object.entries(object)) {
    console.log(key, value);
}

Anyway, from a code-style point of view, you should still check whether your object is an array before you iterate over it. You can use Array.isArray to achieve that. So, assuming data is either an object or an array:

if (Array.isArray(data)) {
    for (const element of data) {
        // Iterate over array
    }
}
else {
    for (const [key, value] of Object.entries(data)) {
        // Iterate over object
    }
}

Generic looping

Since in JavaScript, typeof [] === "object" (i. e. arrays are objects that use the element's index as its key), you could reduce it to a single loop with Object.entries:

for (const [key, value] of Object.entries(data)) {
    // For arrays, `key` will be the index
}

Beware though that this latter method will not do justice to your exclusion of dynamic properties (e. g. array.foo), as you'll iterate over the result of Object.entries. If you do need to make this exclusion, use two for..of loops with Array.isArray as shown above.

like image 178
Chiru Avatar answered Sep 20 '26 22:09

Chiru



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!