javascript JS递归遍历对象 使用for(variable in object)或者叫for/in和forEach方式
1.递归遍历查找特定key值(ie9以下不支持forEach)
原文http://www.cnblogs.com/ae6623/p/5938560.html
var obj = { first: "1", second: { name: "abc", mykey: "2", third: { age: "30", mykey: "3" } }, forth: "4", mykey: "5" }; console.log(getMykey(obj, [])); function getMykey(obj, mykeyValues) { //没有则跳出 if (!obj["mykey"]) { return mykeyValues; } else { //有就放入 mykeyValues.push(obj["mykey"]); //再次递归 var keys = Object.keys(obj); keys.forEach(function(i) { getMykey(obj[i], mykeyValues); }); } return mykeyValues; }
2.递归遍历输出key
参考http://www.jb51.net/article/86607.htm
要求输出嵌套json对象的key name
LG: var tree = {node1:{node2:"",node3:{node4:""}}} Print: ["node1","node2","node3","node4"]
答案:
var arr=[]; function printTree(tree){ for(var i in tree){ arr.push(i); typeof tree[i]=='object'?printTree(tree[i]):''; }; }(tree); console.log(arr);
var obj ={first:"1",second:{name:"abc",mykey:"2",third:{age:"30",mykey:"3"}},forth:"4",mykey:"5"};console.log(getMykey(obj, []));functiongetMykey(obj, mykeyValues) {//没有则跳出if (!obj["mykey"]) {return mykeyValues;}else{//有就放入mykeyValues.push(obj["mykey"]);//再次递归var keys =Object.keys(obj);keys.forEach(function(i) {getMykey(obj[i], mykeyValues);});}return mykeyValues;}