【发布时间】:2012-01-17 23:02:19
【问题描述】:
我有一个这样的 json 对象:
[{
"thing": "Top",
"data": {
"childs": [{
"thing": "a",
"data": {
"text": "sdfgdg1",
"morestuff": {
"thing": "Top",
"data": {
"childs": [{
"thing": "a",
"data": {
"text": "sdfg2",
"morestuff": "",
}
},
{
"thing": "a",
"data": {
"text": "gfhjfghj3",
"morestuff": {
"thing": "Top",
"data": {
"childs": [{
"thing": "a",
"data": {
"text": "asdfsadf 2 4",
"morestuff": {
"thing": "Top",
"data": {
"childs": [{
"thing": "a",
"data": {
"text": "asdfsadf 2 5",
"morestuff": {
"thing": "Top",
"data": {
"childs": {
"thing": "a",
"data": {
"text": "asdfsadf 2 6",
"morestuff": "",
},
"data": {
"text": "asdfsadf 2 6",
"morestuff": "",
}
},
}
},
}
}],
}
},
}
}],
}
},
}
}],
}
},
}
},
{
"thing": "a",
"data": {
"text": "asdfasd1 2",
"morestuff": {
"thing": "Top",
"data": {
"childs": [{
"thing": "a",
"data": {
"text": "asdfsadf 2 3",
"morestuff": "",
}
}],
}
},
}
},
{
"thing": "a",
"data": {
"text": "dfghfdgh 4",
"morestuff": "",
}
}],
}
}]
...我正在尝试遍历它并获得“文本”对象的总数。
我似乎无法让递归工作..我想我缺少对 json 和递归的基本理解..
经过几天的变化:
count=0;
c2=0;
c3=0;
function ra(arr){
//console.log(arr.data.morestuff)
if(arr!==undefined && arr.data && arr.data.morestuff===""){
c3++;
}else if((arr && arr.data && typeof arr.data.morestuff==="object")){
if(arr.data.morestuff.data.childs.length>1){
for(var w=0;w<arr.data.morestuff.data.childs.length;w++){
count+=ra(arr.data.morestuff.data.childs[w])
}
}else{
count+=ra(arr.data.morestuff.data.childs[0])
}
}
return(c3)
}
countn=0;//top morestuff with no morestuff
tot=0;
function reps(obj){
tot=obj.data.childs.length;
console.log("tot="+tot)
for(var x=0;x<tot;x++){
tot+=ra(obj.data.childs[x])
c3=0
if(tot>1000){//trying to prevent a runaway loop somehwere
break;
}
}
console.log(tot)
}
reps(json[0]);
我得出的结论是我不知道。我得到了各种不同的结果;有些通过将 ra 方法的返回相加而接近,但没有一致(即错误)并且总是至少相差一些。
JSON 是一致的,尽管有未知数量的孩子和孩子的孩子,这就是我寻求递归的原因。
这是一个小提琴:http://jsfiddle.net/CULVx/
理想情况下,我想计算每个文本对象、它的相对位置以及它拥有的子对象的数量,但我想如果我能让计数工作,我可以把这些东西放入一个数组中。 ..
注意:我尝试过 jsonParse 和其他库均无济于事。特别是,当试图在这个 json 上使用它时,jsonParse 会抛出一个Object has no method "match" 错误。
【问题讨论】:
-
您在最嵌套的对象中有两个
data属性 - 对吗? -
@pimvdb 是的,但是在任何给定的
morestuff属性中可以有任意数量的data道具
标签: javascript json recursion