I want to pass some data through a for...in
loop. I need to check if the data type of data
(which is unknown until runtime) makes sense to run through that loop first. All of Array
, Object
, and String
are valid, but if data instanceof String
then data[i]
is still valid and returns the character in data
at position i
. I only want to get entire values (i.e. other scalars and objects), not parts of strings. I’m not sure if there are data types other than Array
and Object
that can contain multiple values and therefore make sense to loop over.
What’s a good test for such an object? This is what I’ve got so far, but I don’t know if it covers all cases.
if (typeof data === "object" && (data instanceof Array || data instanceof Object)) {
for (let i in data) {
// ...
}
}
I’ve also looked at iterable, but Object
s aren’t iterable, only Array
s.
2
Answers
Given that Object.keys function is safe to pass any data type
And MDN claims Object.keys is synonymous with the underworking of for..in… You should be safe attempt to iterate over any object without the test and non-qualifying data types will result in a noop scenario.
Now, a more explicit check for your requirements would be as follows:
This check would permit all values other than string types and String object instances to enter the for loop.
It is more readable since it says which of the for…in type candidates you want to exclude. And that should address your speculation as to which data types are valid candidates in a for..in iteration.
What about just
This covers any potential secret iterable structures that you might have to handle, and excludes all numbers, strings, undefineds, etc list here