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.