js递归遍历key
需求:根据Json对象,查找到某key所有值
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;
}
运行结果如下:
检索mykey的值为:["5","2","3"]