2

How can I check the object or variable is traversable in Javascript or jQuery?

An object or a variable which is traversable must works in for each like object.forEach() and $.each(object, callback) in jQuery.

Actually I want to validate it then use it in for each loops.

Update:

The solution which I looking for is something like this:

if(is_traversable($var)) {
    $var.forEach(function(value, key) {
        console.log(value);
    }
}

And you may give me an implementation of is_traversable() function.

Milad Rahimi
  • 3,464
  • 3
  • 27
  • 39

4 Answers4

2

For arrays, use Array.isArray() and for objects, you could first check not null and typeof is equal to 'object' or 'function'.

The wanted function for it:

var isTraversable = o => Array.isArray(o)
     || o !== null && ['function', 'object'].includes(typeof o);

console.log(isTraversable());               // false
console.log(isTraversable(undefined));      // false
console.log(isTraversable(null));           // false
console.log(isTraversable(''));             // false
console.log(isTraversable(0));              // false
console.log(isTraversable('a'));            // false
console.log(isTraversable(42));             // false
console.log(isTraversable(/./));            // false
console.log(isTraversable([]));             // true
console.log(isTraversable([1]));            // true
console.log(isTraversable({}));             // true
console.log(isTraversable({ a: /./ }));     // true
console.log(isTraversable(function () {})); // true
console.log(isTraversable(() => true));     // true
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Similarly you can use typeof to detect the type. I believe arrays will list as objects though so use caution. – Liam MacDonald Sep 05 '16 at 13:26
  • but `null` is an object and not iterable. – Nina Scholz Sep 05 '16 at 13:28
  • @NinaScholz null is not an object. Apparently `typeof null` is a bug in ecmascript when it outputs 'object' – Flame Sep 05 '16 at 13:33
  • Actually, there was a proposal to make `typeof null == "null"`, which was rejected: http://wiki.ecmascript.org/doku.php?id=harmony%3atypeof_null – Gerardo Furtado Sep 05 '16 at 13:36
  • 1
    This is not traversable : {} and [] , so you need to check also the length or if there is anything inside the object after it is the correct type with for( var p in o ) { return true; }. A string is also traversable when it is not empty. An object can be also a primitive type like a boolean or a number. These are not traversable. – Codebeat Aug 22 '18 at 21:31
  • This answer is incorrect. Functions are traversable like any other object, but this solution returns false for them. – luawtf Mar 13 '21 at 19:57
0

You can use the following and create appropriate functions / validations:

var myArray = ["This is a test"];
var myObject = {"test" : "This is a test"};

if( Object.prototype.toString.call( myArray ) === '[object Array]' ) {
    alert( 'Array!' );
}

if( Object.prototype.toString.call( myObject ) === '[object Object]' ) {
    alert( 'Object!' );
}

Check out this one : Object.toString

Strahdvonzar
  • 400
  • 2
  • 10
0

forEach and friends are implemented in a generic fashion, to be eligible, their argument

  • must support the getter operator ([])
  • and must have a numeric length property.

That is, any string and any object with .length will work:

isIterable = x => x && !isNaN(x.length);

Note that for..of is different from forEach, it explicitly requires an argument to have Symbol.iterator.

a = {
    length: 10,
    5: 555
};

[].forEach.call(a, x => console.log(x)); // fine

for(var x of a) console.log(x); // no way
georg
  • 211,518
  • 52
  • 313
  • 390
0

items might be Array Object, variable

Example

items = [1,2,3,4]; or items = { name: 'abc', email: 'abc@xyz.com'}

var items;

if (items && items instanceof Array) { // if Array
  items.forEach(function(value) {
    console.log(value);
  });
} else if (items && items instanceof Object) { // if Object
  for (key in items) {
    console.log(items[keys]);
  }
} else { // if variable 
  console.log(items);
}
nmanikiran
  • 2,866
  • 15
  • 19