var obj = {
a: 'b',
c: 3,
e: [
3,
null,
'24',
function() {},
undefined,
NaN,
Infinity,
new Date(),
/ff/
]
};
/*
`o` is an object with the following keys:
`kind` is one of 'array', 'object', 'number', 'string', 'null', 'function', 'regexp', 'date', 'undefined'
`value` is the item value itself
`parent` is the item's parent element or null if root element
`arg` is the array index or object key, respectively for children of arrays or objects
*/
var onItem = function(o) {
console.log( [o.value, o.kind, o.parent ? o.parent.kind : 'root', o.arg].join(' | ') );
};
// `onItem` will be called for every item
traverse(obj, onItem);
it prints:
"[object Object] | object | root | "
"b | string | object | a"
"3 | number | object | c"
"3,,24,function () {},,NaN,Infinity,Wed Jan 28 2015 15:41:58 GMT+0000 (WET),/ff/ | array | object | e"
"3 | number | array | 0"
" | null | array | 1"
"24 | string | array | 2"
"function () {} | function | array | 3"
" | undefined | array | 4"
"NaN | number | array | 5"
"Infinity | number | array | 6"
"Wed Jan 28 2015 15:41:58 GMT+0000 (WET) | date | array | 7"
"/ff/ | regexp | array | 8"
check it out here: jsbin