skip to Main Content

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 Objects aren’t iterable, only Arrays.

2

Answers


  1. Given that Object.keys function is safe to pass any data type

    Object.keys(1) // []
    Object.keys('f') // ['0']
    Object.keys(false) // []
    Object.keys(new Date()) // []
    Object.keys(BigInt("123456789012345678901234567890")) // []
    Object.keys({foo: 1}) // ['foo']
    Object.keys(['foo', 'bar']) // ['0', '1']
    

    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:

    if (typeof data !== "string" || !(data instanceof String)){ ... }
    

    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.

    Login or Signup to reply.
  2. What about just

    if (typeof data === "object")
    

    This covers any potential secret iterable structures that you might have to handle, and excludes all numbers, strings, undefineds, etc list here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search