Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosePedroDias/91439ed34b5a7ae19476 to your computer and use it in GitHub Desktop.
Save JosePedroDias/91439ed34b5a7ae19476 to your computer and use it in GitHub Desktop.
traverses json collections.

usage

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

var _traverse = function trav(o, parent, arg, onValue) { // onValue({value, kind, parent, arg})
var data = {value:o, parent:parent, arg:arg};
var to = typeof o;
if (to === 'string') {
data.kind = 'string';
onValue(data);
}
else if (to === 'object') {
if (o === null) {
data.kind = 'null';
onValue(data);
}
else if (o instanceof Array) {
data.kind = 'array';
onValue(data);
for (var i = 0, I = o.length; i < I; ++i) {
trav(o[i], data, i, onValue);
}
}
else if (o instanceof Date) {
data.kind = 'date';
onValue(data);
}
else if (o instanceof RegExp) {
data.kind = 'regexp';
onValue(data);
}
else {
data.kind = 'object';
onValue(data);
for (var k in o) {
if (o.hasOwnProperty(k)) {
trav(o[k], data, k, onValue);
}
}
}
}
else if (to === 'function') {
data.kind = 'function';
onValue(data);
}
else {
data.kind = (to === 'number') ? 'number' : 'undefined';
onValue(data);
}
};
var traverse = function(o, onValue) {
_traverse(o, null, null, onValue);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment