Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //your object
- var o = {
- foo:"bar",
- arr:[1,2,3],
- subo: {
- foo2:"bar2"
- }
- };
- //called with every property and it's value
- function process(key,value) {
- log(key + " : "+value);
- }
- function traverse(o,func) {
- for (i in o) {
- func.apply(this,[i,o[i]]);
- if (typeof(o[i])=="object") {
- //going on step down in the object tree!!
- traverse(o[i],func);
- }
- }
- }
- //that's all... no magic, no bloated framework
- traverse(o,process);
- $.each(myJsonObj, function(key,val){
- // do something with key and val
- });
- function traverse(jsonObj) {
- if( typeof jsonObj == "object" ) {
- $.each(jsonObj, function(k,v) {
- // k is either an array index or object key
- traverse(v);
- }
- }
- else {
- // jsonOb is a number or string
- }
- }
- function js_traverse(o) {
- var type = typeof o
- if (type == "object") {
- for (var key in o) {
- print("key: ", key)
- js_traverse(o[key])
- }
- } else {
- print(o)
- }
- }
- js> foobar = {foo: "bar", baz: "quux", zot: [1, 2, 3, {some: "hash"}]}
- [object Object]
- js> js_traverse(foobar)
- key: foo
- bar
- key: baz
- quux
- key: zot
- key: 0
- 1
- key: 1
- 2
- key: 2
- 3
- key: 3
- key: some
- hash
- function traverse(o,func) {
- for (i in o) {
- func.apply(this,[i,o[i]]);
- if (typeof(o[i])=="object") {
- //going on step down in the object tree!!
- traverse(o[i],func);
- }
- }
- }
Add Comment
Please, Sign In to add comment