我有以下示例对象:
{
"sampleA":{
"sampleB1":{
"sampleC1":{
"sample1":"sample",
"sample2":"sample",
"sample3":"sample",
"sample4":"sample",
"sample5":"sample"
},
"sampleB2":{
"sample1":"sample",
"sample2":"sample sample",
"sample3":"sample",
"sample4":"sample sample",
"sample5":"sample sample",
"sample6":"sample"
},
"sampleB3":{
"sample1":"sample",
"sample2":"sample sample",
"sample3":"sample sample",
"sample4":"sample sample",
"sample5":{
"sample6":"sample",
"sample7":"sample sample",
"sample8":"sample sample",
"sample9":"sample sample",
"sample10":"sample",
"sample11":"sample"
},
"sample100":"sample"
}
}
}
}
这是一个可以嵌套到任何级别的JS对象。我正在尝试遍历对象并执行一些操作:
以下是我的代码:
function isLeafNode(node) {
if (typeof node == typeof "string") {
return true;
} else {
return false;
}
}
iterateObject(jsonData);
function iterateObject(obj) {
for (var key in jsonData) {
if (jsonData.hasOwnProperty(key)) {
if(!isLeafNode(jsonData[key])){
iterateObject(jsonData[key])
}else{
console.log("leaf node")
//do something
}
}
}
}
但是上面的代码导致无限循环。我做错了什么?
答案 0 :(得分:2)
您需要引用obj
内的本地iterateObject
,而不是全局jsonData
。
function iterateObject(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (!isLeafNode(obj[key])) {
iterateObject(obj[key]);
} else {
console.log(key, "leaf node");
}
}
}
}
function isLeafNode(node) {
return typeof node === "string";
}
var data = { sampleA: { sampleB1: { sampleC1: { sample1: "sample", sample2:"sample", sample3:"sample", sample4:"sample", sample5:"sample" },sampleB2: { sample1: "sample", sample2:"sample sample", sample3:"sample", sample4:"sample sample", sample5:"sample sample", sample6:"sample" },sampleB3: { sample1: "sample", sample2:"sample sample", sample3:"sample sample", sample4:"sample sample", sample5:{ sample6: "sample", sample7:"sample sample", sample8:"sample sample", sample9:"sample sample", sample10:"sample", sample11:"sample" },sample100: "sample" } } } };
iterateObject(data);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)
您的以下功能存在问题
function iterateObject(obj) {
for (var key in jsonData) {
if (jsonData.hasOwnProperty(key)) {
if(!isLeafNode(jsonData[key])){
iterateObject(jsonData[key])
}else{
console.log("leaf node")
//do something
}
}
}
}
应该如下所示
function iterateObject(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if(!isLeafNode(obj[key])){
iterateObject(obj[key])
}else{
console.log("leaf node")
//do something
}
}
}
}
您在循环中使用 jsonData 而不是传递参数 obj